Chamindu
Chamindu

Reputation: 716

How to model recursive relationships in DDD

How can i model a hierarchical relationship in a DDD domain model? In my app I have a Organization entity and organizations can have divisions and divisions in turn can have child divisions. The nesting depth is arbitrary. How should I design my entities and repositories?

Upvotes: 2

Views: 1428

Answers (1)

eulerfx
eulerfx

Reputation: 37709

A simple model could look something like:

public class Organization : Division 
{
  public Organization(string name)
    : base(name)
  {
  }
}

public class Division
{
  public Division(string name, Division parent = null)
  {
    this.Name = name;
    this.Parent = parent;
  }
  public string Name { get; private set; }
  public Division Parent { get; private set; }
  public ICollection<Division> Divisions { get; private set; }
  public Division AddDivision(string name)
  {
     var division = new Division(name, this);  
     this.Divisions.Add(division);
     return division;
  }
}

There are other approaches as well depending on specific needs. If using an ORM such as NHibernate to implement repositories take a look at this to see how to store and query hierarchical relationships.

Upvotes: 4

Related Questions