实体框架核心:与同一实体的多对多关系

时间:2016-09-29 13:33:57

标签: c# linq asp.net-core .net-core entity-framework-core

我正在尝试映射与同一实体的多对多关系。 User实体的IList<User>数据字段为Contacts,用于存储用户&#39}。联系人/朋友信息:

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

当我尝试使用流畅的API来映射这么多对多的关系时,它给我带来了一些麻烦。显然,当我在HasMany()属性上使用user.Contacts时,它没有WithMany()方法来接下来调用。 Visual Studio中的intellisense仅显示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 

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

1 个答案:

答案 0 :(得分:23)

  

那么为什么会这样呢?我有什么不对的地图   多对多的关系?

不,你没有做错任何事。 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);