Domain Driven Design – Many to Many Relations

aggregatedomain-driven-designrelationships

I am new at domain driven design, and want to learn some about aggregates. For example I have a User and Role entities.

public class User {
    public string Id {get; set;}
    public string Username {get; set;}
    public IEnumerable<Role> Roles {get; set;}
}

public class Role {
   public string Id{get; set;}
   public string Name {get; set;}
}

In this stuation, User is an aggregate root. Roles are part of user. But If I want to use Many-to-many relations with Role and User, how changes the aggregation? In this stuation which is the aggregate root?

Best Answer

Just because you have a many to many relationship at a data or database level, doesn't mean it has to be represented in code. You should model for the relationships you care about or are useful to you. The relationship of roles to users is more of an implementation detail and not something worth modelling at all at a code level, let the database handle the consistency. Knowing all the users in a role seems like more of a user search capability than anything useful in working with a role.

In either case you really don't want to model both directions of a many to many case in code at the same time, because you will run into circular reference and consistency issues. Databases are designed to handle that consistency gracefully, let them do the hard work and only model the relationship in one direction at a time in code. Chances are your users are really only interested in one direction of such relationships at a time anyway.