Search code examples
architectureentitydomain-driven-designddd-repositories

Load domain entity's child collections in DDD


I have an aggregate which is constituted of a root entity called Master and a leaf called Detail. So the Master entity has a collection of Detail entities. I don't expose the Details collection to the client because I don't want to let the client add Detail items to it directly. Instead, I have an AddDetail method on my Master entity which verifies the domain invariants as soon as the new Detail item is being added and allows us to apply our domain rules at that place.The Details is exposed as an readonly IEnumerable property. The problem comes when I want to load the Details item in my MasterRepository. Since no item can be added to the Details collection, I don't know how to load the Details which are part of the state of the Master entity. On the other hand I don't think it is a good practice to use the AddDetail method while loading the Master entity's state, because at that time the rules are already applied and it would be a redundant overload to verify them while loading the entity's state. Plus, adding a new Detail, triggers some domain events which I don't want to happen while loading the entities.


Solution

  • I don't think it is a good practice to use the AddDetail method while loading the Master entity's state

    You are right that usage of the AddDetail method is not a good idea.

    I don't know how to load the Details which are part of the state of the Master entity.

    How do you load other properties of your Master entity?

    There are a lot of available options I mentioned answering another question (How to retrieve Domain Object from Repositories) :

    1. ORMs can map private fields (e.g. NHibernate, EntityFramework).
    2. Reflection can be used to access private fields.
    3. The collection can be passed via public constructor that is used to construct an entity. I would avoid using public setters for collections.
    4. 3-rd part frameworks can be useful sometimes (e.g. AutoMapper)

    Since collection of Detail entities is simply a Master's property I would use an approach that is used for loading other properties.