entity-frameworkmany-to-manymodelbinder

Many-To-Many relationship mapping using a mapping table


I Have the following tables

Users
-> UserId
-> Name

Roles
-> RoleId
-> Name

UserRoles
-> UserId
-> RoleId

and the following classes

public class Role{
     public int RoleId{get;set;}
     public int Name{get;set;}
}

public class User{
     public int UserId{get;set;}
     public int Name{get;set;}
     public ICollection<Role> Roles{get;set;}
}

How to map this using EntityFramework ModelBinder.


Solution

  • protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(u => u.Roles)
            .WithMany()
            .Map(a => {
                a.ToTable("UserRoles");
                a.MapLeftKey("UserId");
                a.MapRightKey("RoleId");
            });
    }