2016-09-29 180 views
7

我想要映射与同一个实体的多对多关系。该User实体有ContactsIList<User>数据字段,用于存储用户的联系人/朋友信息:实体框架核心:与同一个实体的多对多关系

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

当我试图用流利的API映射这个多对多的关系,它给我带来些麻烦。显然,当我在user.Contacts属性上使用HasMany()时,它没有WithMany()方法可以调用下一个。 Visual Studio的智能感知只显示WithOne(),但不显示WithMany()

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

那么为什么会发生这种情况呢?有什么我做错了映射这种多对多的关系?

+0

你可以看看这个:https://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many –

回答

15

那么为什么会发生这种情况呢?有什么我做错了地图这个多对多的关系吗?

不,你没有做错任何事。 It's just not supported。当前状态here

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

对于EF-Core,您应该为映射表创建实体。如UserContacts。正如评论中提到的docs中的完整示例。我没有实际测试下面的代码,但它应该是这个样子:

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<UserContacts> Contacts { get; set; } 
} 

和你modelBuilder

modelBuilder.Entity<UserContacts>() 
     .HasOne(pt => pt.Contact) 
     .WithMany(p => p.Contacts) 
     .HasForeignKey(pt => pt.ContactId); 

    modelBuilder.Entity<UserContacts>() 
     .HasOne(pt => pt.User) 
     .WithMany(t => t.Contacts) 
     .HasForeignKey(pt => pt.UserId); 
+0

在第一modelBulder.Entity,它应该是“.WithMany(p => p.Users)”而不是“.WithMany(p => p.Contacts)”? –

+0

@CarlosAdrián - 我想不是。因为它是对同一张表的引用。它仍然是一个拥有多个联系人的用户。联系人仍然是用户。 – smoksnes