ef code first - Entity Framework - How to configure the User Roles Many to Many Relationship -


below definition of user entity, there 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 definition of role entity

public class role {     public string id { get; set; }     public string name { get; set; }     public string description { get; set; } 

what want define many many relationship , generate relationship table userrole use userid left key , roleid right key, how write configuration code?

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 onmodelcreating method in 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");         }); } 

Comments