-->

Reference another aggregate root in child entity?

2020-07-26 11:09发布

问题:

I wanna model Order and Product concept with the help of DDD but I wonder how to deal with it.

Suppose you have Order class that has OrderItem class as it's child and Order is Aggregate Root, and Order class has list of OrderItems and every OrderItem has a reference to Product Class. Product is Aggregate Root of course. I mean some thing like this :

public class Order{
...
public list<OrderItem> OrderItems {get;set;}
}

public class OrderItems{
...
public int Qty {get; set;}
public Product {get; set;}
}

public class Product{
...
}

but as far as i know I can't have a reference from child of Order Aggregate to Product Aggregate. how to deal with this ?

Tnx in forward.

回答1:

At the page 202 of book Architecting application for the enterprise you could see an image. There are various bounded context, two of them are really simialr to what you need. Order is an aggregate root, having Order Detail as its child. Order Detail in turn has a relationship with Product that is the aggegate root of an aggregate in a different bounded context.

So the first thought is that Product belongs to Order aggregate. However, next you might find out that use-case exist to treat products outside of orders-for example for the catalog of products. This makes up for another aggergate rooted in Product.

So... yes, a child of an aggregate can hold a reference to another aggregate root (even in different bounded context).

Is this a right choice? The right answer in a case like that is always: depends. On what? On business rules, and how you have to handle the aggregate that will be "swallowed" (Product) by another bigger aggregate (Order).