When modeling bigger domain entities you will probably have some kind of relation between these entities. These relations will usually result in entities referencing different entities. If i am not mistaken, there are two ways of modeling these relations:
- Aggregation ( A uses B )
- Composition ( A owns B )
When modeling Composition the root entity manages the lifetime of it's composited entities. That also applies to persistence, where you have to clean up the composited entities, when the root entity is deleted.
What i am having trouble with is the same scenario, just using Aggregation. How do you model the relation between entities, when they can exist independently and the same entity could be aggregated by multiple root entities? This gets even more complicated when both entities are supposed to be saved to a database.
Take these requirements for example:
We want to model recipes, which consist of different ingredients and their quantities. Recipes and ingredients can be provided with additional information, like descriptions, pictures and user comments. Ingredients can also be provided with links to substitute ingredients and recipes to make the ingredients (bread can be made using a recipe for example).
I would start by separating the different domain entities, specified by the requirements and add the fields that are owned by the entities (composition). That would be information like comments, pictures and descriptions. But i don't know how to correctly model the aggregation between the entities, so that independent handling makes sense and i can easily integrate it in my Data Access Layer (database).
Could you provide me with a short code example that demonstrates how i should model the relation between Recipe
and Ingredient
, so that i can use it easily in my application and don't have a nightmare in my persistence code? Use your language of choice!