Home > Back-end >  EF Core: Many to Many relationship without navigational entity collections
EF Core: Many to Many relationship without navigational entity collections

Time:11-26

I want to implement a model abiding by the principles of DDD & aggregates.

I have a many-to-many relationship between a Company & User, but these are both aggregate roots, and I want to model their relationship by referencing Ids not the entity types i.e.

public class Company
{
    public List<int> UserIds { get; set; }
}

public class Users
{
    public List<int> CompanyIds { get; set; }
}

Is it possible to use the Fluent model builder API to allow this? i.e. so that it would build a many-to-many table consisting of the columns: | UserId | CompanyId |

CodePudding user response:

Sure, you'd just be opting-out of the convenient and useful EF Many-to-many pattern, which has a hidden linking table, and adding a first-class linking entity. eg

public class Company
{
    public List<CompanyUser> CompanyUsers { get; set; }
}

public class Users
{
    public List<CompanyUser> CompanyUsers { get; set; }
}

public class CompanyUser
{
    public int CompanyId {get;set;}
    public int UserId {get;set;}
}

And configure CompanyUser to have its key on (CompanyId,UserId) and an alternate key (or unique constraint) on (UserId, CompanyId).

It's obviously more convenient to put CompanyUser.Company and CompanyUser.User Navigation Properties on the linking entity, but entirely optional.

  • Related