Search code examples
entity-frameworkef-code-firstef-code-first-mapping

Entity Framework - How to configure the User Roles Many to Many Relationship


Below is the definition of the User entity, there is a navigation property Roles

    public class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Id { get; set; }

        public string Username { get; set; }

        public virtual ICollection<Role> Roles { get; set; }

Below is definition of the Role entity

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

What i want is to define the many to many relationship and generate a relationship table UserRole which use UserId as the left key and RoleId as the right key, so how to write the configuration code?


Solution

  • User:

    public class User
    {
        public User()
        {
            Roles = new List<Role>();
        }
    
        public string Id { get; set; }
        public string Username { get; set; }
        public virtual ICollection<UserRole> Roles { get; set; }
    }
    

    Role:

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

    UserRole:

    public class UserRole
    {
        public string Id { get; set; }
        public string UserId { get; set; }
        public string RoleId{ get; set; }
    
        public virtual User User { get; set; }
        public virtual Role Role { get; set; }
    }
    

    Override the OnModelCreating method in your dbcontext:

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