[Question]: DDD to remove an order item
See original GitHub issueHi,
Iâm looking at DDD and how we can remove items from a collection.
In the Order microservice the Order
entity has a list of OrderItems
which can only be added to via the Order
aggregate method.
How would we go about removing an order item from the Order? If we go the same route of encapsulation then we would have a method such as:
public void RemoveOrderItem(OrderItem orderItem)
{
_orderItems.Remove(orderItem);
}
But this wouldnât actually remove it as it needs to be removed via Entity Frameworkâs Remove()
method on the DbContext
.
So this would require either a new IOrderItemRepository
or an additional method on the IOrderRepository
to make use of the DbContext.
However, this breaks the encapsulation pattern as it can be done from outside the Order aggregate.
Is there a way round this? Or am I missing the right way of doing this?
Thanks
Issue Analytics
- State:
- Created 5 years ago
- Reactions:6
- Comments:12
Top GitHub Comments
Why is there no method for removing OrderItems on the Order Aggregate? Rather than addressing the problem in a blog post, how about implementing this into the app, to show folks the proper way of removing a collection from an aggregate and demonstrate it how persists that change all the way down to the DB?
Good question. đ So, you are right in the Aggregateâs implementation. Youâd implement a method called RemoveOrderItem in the Order AggregateRoot where youâd remove the item from the Orderâs Item list, so in that method you are encapsulating and you could also implement additional âin-memoryâ behavior in that method, thaâs why you donât want to provide direct access to the Itemâs List.
Then, to your question, the Repository you have to use is just the OrderRepository (1:1 relationship with the aggregate) and call the OrderRepository.Update(order) method.
Sure, you are âremoving/deletingâ an order item, but from an Aggregate perspective, that is an Update/change within the order. If you had to add/change anything else for deleting Order items, youâd need to do it within the method OrderRepository.Update(order).
You MUST NOT create repositories per child entities or tables that are âchildâ within an aggregate (like Order). Repositories must have a 1:1 relationship with aggregates and therefore with the aggregateRoot or Root Entity (Order in this case).
The encapsulation is maintained that way. The Order aggregate controls invariants and behavior of anything in-memory within the Aggregate. The Repository controls the infrastructure persistence for that Aggregate.
Read this chapter I wrote where all the repository implementation is explained in deeper details and why it is important to âEnforce one aggregate root per repositoryâ:
https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design
Hope that helps. đ