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

0 تعليقات

إرسال تعليق

Post a Comment (0)

أحدث أقدم
NERV Open Source

Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.

Explore NERV on GitHub →