2017-02-04 83 views
-1

我需要在DTO中應用業務規則,但此DTO具有N個實體的屬性。如何在DTO中應用業務規則DDD

我想知道驗證此DTO的正確方法。

+0

如果您希望確保他們正在整理來自多個實體的正確數據項,那麼您的DTO中不應該有業務規則,我會在單元測試中針對DTOMapping服務執行此操作。 –

+0

我不明白這個問題。給我舉個例子。 –

+0

你做**不需要**,你**決定**來。完全沒有理由**要驗證您的DTO是否違反業務規則,或者您的設計出現問題。 **詳細信息**您的**背景**和您的**期望值**以獲得正確的答案。 –

回答

0

非常普遍的做法是將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); 
0

由於DTO只是一個數據傳輸對象,它不應該應用任何業務邏輯。

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創建面層的黑色盒子

0

在其他的答案已經指出:

你不應該在你的DTO的業務規則。

雖然,當話題是DDD,另一個很常見的方法,以確保你總是創建有效的域對象是使用Builder Pattern

此模式允許您改變產品的表示。例如,軟件可以有一個域計價產品,但是 - 在現實世界中的表示 - 這可能是一個服務材料(我可以賣一個手機或手機保險),於是兩個建設者必須(MaterialBuilderServiceBuilder,即ie),它們構建相同的域對象Product

這種圖案通常使用具有方法鏈接並導致連貫接口