Question

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.

Was it helpful?

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.

OTHER TIPS

You did not say which language you are using, but ORM frameworks usually use direct access to the internal fields of the Master via reflection.

If you roll your own or use a language without reflections, you can add an internal utility class (e.g., in the same package) that has package/friend access to the fields and can be used by the Repositories to access the fields directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top