Learn Many to Many Relationship in Entity Framework
An example of many-to-many relationship is asp's membership tables, between aspnet_Users and aspnet_Roles. Usually we declare it like t...
https://www.czetsuyatech.com/2012/01/c-many-to-many-on-ef.html
An example of many-to-many relationship is asp's membership tables, between aspnet_Users and aspnet_Roles.
Usually we declare it like this:
public class AspUser {
public Guid UserId { get; set; }
...
public ICollection AspRoles { get; set; }
}
public class AspRole {
public Guid RoleId { get; set; }
...
public ICollection AspUsers { get; set; }
}
This will create a new table AspUsersAspRoles with UserId, and RoleId as columns.
If you want to define your own table name (example AspUsersInRoles) you just need to override OnModelCreating:
modelBuilder.Entity() .HasMany (r => r.AspRoles) .WithMany(u => u.AspUsers) .Map(m => { m.ToTable("AspUsersInRoles"); m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); });




Post a Comment