entity framework核心:与同一实体的多对多关系

我试图与同一个实体映射多对多关系。 User实体具有用于ContactsIList数据字段,用于存储用户的联系人/朋友信息:

 public class User : DomainModel { public virtual IList Contacts { get; protected set; } //irrelevant code omitted } 

当我尝试使用流畅的API来映射这么多对多的关系时,它给我带来了一些麻烦。 显然,当我在user.Contacts属性上使用HasMany()时,它没有WithMany()方法来调用next。 Visual Studio中的intellisense仅显示WithOne() ,但不显示WithMany()

 modelBuilder.Entity().HasMany(u => u.Contacts).WithMany() // gives compile time error: CS1061 'CollectionNavigationBuilder' does not contain a definition for 'WithMany' and no extension method 'WithMany' accepting a first argument of type 

那么为什么会这样呢? 有没有什么我做错了映射这种多对多的关系?

那么为什么会这样呢? 有没有什么我做错了映射这种多对多的关系?

不,你没有做错任何事。 它只是不受支持 。 目前的状态。

尚不支持没有实体类来表示连接表的多对多关系。 但是,您可以通过包含连接表的实体类并映射两个单独的一对多关系来表示多对多关系。

使用EF-Core,您应该为映射表创建实体。 比如UserContacts 。 如评论中所述, 文档中的完整示例。 我实际上没有测试下面的代码,但它应该看起来像这样:

 public class UserContacts { public int UserId { get; set; } public virtual User User { get; set; } public int ContactId { get; set; } // In lack of better name. public virtual User Contact { get; set; } } public class User : DomainModel { public List Contacts { get; set; } } 

和你的modelBuilder

  modelBuilder.Entity() .HasOne(pt => pt.Contact) .WithMany(p => p.Contacts) .HasForeignKey(pt => pt.ContactId); modelBuilder.Entity() .HasOne(pt => pt.User) .WithMany(t => t.Contacts) .HasForeignKey(pt => pt.UserId); 

可能是我迟到了,但@smokesnes,答案对于同一实体到entity framework版本2.1的多对多关系不起作用。 但他的答案对于与不同实体的多对多关系会很好。

以下是同一实体(多达EF Core 2.1)的多对多关系的解决方案

 public class UserContacts { public int UserId { get; set; } public virtual User User { get; set; } public int ContactId { get; set; } public virtual User Contact { get; set; } } public class User : DomainModel { public List UserContacts { get; set; } public List ContactUsers { get; set; } } 

然后在模型构建器中:

 protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .HasOne(pt => pt.User) .WithMany(p => p.UserContacts) .HasForeignKey(pt => pt.UserId); modelBuilder.Entity() .HasOne(pt => pt.Contact) .WithMany(t => t.ContactUsers) .HasForeignKey(pt => pt.ContactId); }