Domain driven design 如何在DTOs DDD中应用业务规则

Domain driven design 如何在DTOs DDD中应用业务规则,domain-driven-design,business-rules,Domain Driven Design,Business Rules,我需要在DTO中应用业务规则,但此DTO具有N个实体的属性 我想知道验证此DTO的正确方法。非常常见的方法是将DTO包装到实体中,并在实体内实现业务规则 var state = new DTO(); var entity = new Entity(state); //this will change the state in a consistent way according to business rules entity.DoSomething1(); entity.DoSomethin

我需要在DTO中应用业务规则,但此DTO具有N个实体的属性


我想知道验证此DTO的正确方法。

非常常见的方法是将DTO包装到实体中,并在实体内实现业务规则

var state = new DTO();
var entity = new Entity(state);

//this will change the state in a consistent way according to business rules
entity.DoSomething1();
entity.DoSomething2();

//this is C#, so I can't get immutable version easily, but if your language allows that - you should return immutable state from entity. Or you can return a clone of the state
state = entity.State;

//store or do whatever you like with the state as long as you keep it immutable.
_repository.Save(state); 

因为DTO只是一个数据传输对象,所以它不应该在内部应用任何业务逻辑

public class Entitity1
{
}

public class Entity2
{
}

public class EntityAggregate
{
    public EntityAggregate(Entity1 entity1, Entity2 entity2) // constructor
    {
        this.entity1 = entity1;
        this.entity2 = entity2;
    }

    public ExecuteYourBusinessCase()
    {
        ... access entity1 and entity2 here and evaluate business logics
    }
}
DTO具有N个实体的属性

更好的方法是为您的案例创建一个聚合类,并在其中应用业务逻辑

public class Entitity1
{
}

public class Entity2
{
}

public class EntityAggregate
{
    public EntityAggregate(Entity1 entity1, Entity2 entity2) // constructor
    {
        this.entity1 = entity1;
        this.entity2 = entity2;
    }

    public ExecuteYourBusinessCase()
    {
        ... access entity1 and entity2 here and evaluate business logics
    }
}

同样值得一提的是,DDD的思想之一是防止创建无效对象。所以您应该保证,若域实体已经创建,那个么它是有效的,并且DTO总是可以创建的。对于负责创建DTO的层来说,业务逻辑仍然是一个黑匣子,如其他答案中所述:


DTO中不应该有业务规则

尽管如此,当主题为DDD时,另一种确保始终创建有效域对象的常用方法是使用

此模式允许您改变产品的表示形式。例如,一个软件可能有一个以领域命名的产品,但在现实世界中,它可能是服务或材料(我可以出售手机或手机保险),因此必须创建两个构建器(MaterialBuilder和ServiceBuilder,例如ie)来构建同一个领域对象,即产品


此模式通常与方法链接一起使用,并产生流畅的界面。

您的DTO中不应该有业务规则,如果您想确保它们对来自多个实体的正确数据项进行排序,我会在针对DTOMapping服务的单元测试中这样做。我不理解这个问题。给我举个例子。你不需要,你决定。绝对没有理由要根据业务规则验证DTO,或者您的设计中存在错误。详细说明你的背景和期望,以获得正确答案。