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");
  });
Many to many relationship in Entity Framework Many to many relationship in Entity Framework Reviewed by Edward Legaspi on Wednesday, January 11, 2012 Rating: 5

No comments:

Powered by Blogger.