[Table("UserMaster")]
public class UserMaster
{
public UserMaster()
{
this.Roles = new List<Role>();
}
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}
[Table("Role")]
public class Role
{
public Role()
{
this.Users = new List<UserMaster>();
}
public int RoleId{ get; set; }
public string Name{ get; set; }
public ICollection<UserMaster> Users { get; set; }
}
I map these tables using EntityTypeConfiguration and it triggers OnModelCreate
this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UsersInRoles");
});
I wonder If there Is a way to map them in the class Role or UserMaster. We can use
[ForeignKey()]
[Key]
[Table()]
Could we do the mapping thing also?
If you want to customize entity framework code first for many to many relationship using data annotation, you must add junction class as the following :
and then related classes must be changed to :
and also see this.