richard
richard

Reputation: 12498

Domain model - What is the proper way for a child to be added to a parent?

I have a parent and child classes. The child doesn't make sense to exist without the parent, and I want the child to have a reference to its parent.

Is this a good way to set up both the reference to the parent in the child and the child being added to the collection on the parent? Or is there a better way to do this?

public class Order
{
     public Guid Id { get; private set; }
     public Name Id { get; private set; }
     IEnumerable<Item> Items { get; private set; }

     public Order(Guid id, string name)
     {
          Id = id;
          name = name;
          Items = new List<Item>();
     }

     public void AddItem(Item item)
     {
            var items = Items.ToList();
            items.Add(item);
            Items  = items;
     }
}

public class Item
{
     public Guid Id { get; private set; }
     public Name Id { get; private set; }
     public Order Order { get; private set; }

     public Item(Guid id, string name, Order order)
     {
          Id = id;
          name = name;
          Order = order;
          Order.AddItem(this);
     }
}

Seems like maybe it's a bad idea to add the child to the parent's collection from within the child, but maybe it is. What's the best way to set up these relationships?

Upvotes: 1

Views: 312

Answers (2)

Leandro Caniglia
Leandro Caniglia

Reputation: 14858

In your case a child should not add itself to the parent collection. A better approach, provided you need the reference to the parent, is to set the parent in the parent, in the same method where the child is added to the list. This would mean setting the item's order right after adding the item to items.

Upvotes: 0

SneakyPeet
SneakyPeet

Reputation: 607

You should ask yourself "why am I trying to find the Order via the Item". Can you genuinely find a good use case?, In this case Order is the aggregate root so you should be operating via the Order. In some cases it might make sense to have a collection of Orders on the Item, if you need to find all the Orders placed on an Item for example. In that case Item will also be an aggregate root.

Upvotes: 0

Related Questions