What Belongs to the Aggregate Root

前端 未结 7 1402
温柔的废话
温柔的废话 2021-01-30 05:43

This is a practical Domain Driven Design question:

Conceptually, I think I get Aggregate roots until I go to define one.

I have an Employee entity, which has sur

7条回答
  •  一向
    一向 (楼主)
    2021-01-30 05:59

    Eric Evan states in his book, Domain-Driven Design: Tackling the Complexity in the Heart of Software,

    An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes.

    There are 2 important points here:

    1. These objects should be treated as a "unit".
    2. For the purpose of "data change".

    I believe in your scenario, Employee and Violation are not necessarily a unit together, whereas in the example of Order and OrderItem, they are part of a single unit.

    Another thing that is important when modeling the agggregate boundaries is whether you have any invariants in your aggregate. Invariants are business rules that should be valid within the "whole" aggregate. For example, as for the Order and OrderItem example, you might have an invariant that states the total cost of the order should be less than a predefined amount. In this case, anytime you want to add an OrderItem to the Order, this invariant should be enforced to make sure that your Order is valid. However, in your problem, I don't see any invariants between your entities: Employee and Violation.

    So short answer:

    I believe Employee and Violation each belong to 2 separate aggregates. Each of these entities are also their own aggregate roots. So you need 2 repositories: EmployeeRepository and ViolationRepository.

    I also believe you should have an unidirectional association from Violation to Employee. This way, each Violation object knows who it belongs to. But if you want to get the list of all Violations for a particular Employee, then you can ask the ViolationRepository:

    var list = repository.FindAllViolationsByEmployee(someEmployee);
    

提交回复
热议问题