ef core many to many

https://stackoverflow.com/questions/46184678/fluent-api-many-to-many-in-entity-framework-core/46184785#46184785

代码如下:

public class Person { public int PersonId { get; set; } public virtual ICollection<PersonClub> PersonClubs { get; set; } } public class Club { public int ClubId { get; set; } public virtual ICollection<PersonClub> PersonClubs { get; set; } } public class PersonClub { public int PersonId { get; set; } public Person Person { get; set; } public int ClubId { get; set; } public Club Club { get; set; } }

The following OnModelCreating would then be used for setup:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PersonClub>() .HasKey(pc => new { pc.PersonId, pc.ClubId }); modelBuilder.Entity<PersonClub>() .HasOne(pc => pc.Person) .WithMany(p => p.PersonClubs) .HasForeignKey(pc => pc.PersonId); modelBuilder.Entity<PersonClub>() .HasOne(pc => pc.Club) .WithMany(c => c.PersonClubs) .HasForeignKey(pc => pc.ClubId); }

猜你喜欢

转载自www.cnblogs.com/dayang12525/p/11239197.html