如何使用ASPNet EF Core创建多对多

时间:2018-01-03 22:32:29

标签: entity-framework asp.net-core

我想在我的应用程序中创建一个联系人列表。因此,我在ApplicationUsers:

之间创建了一个映射表
public class UserContacts
{
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }

    public string ContactId { get; set; }
    public virtual ApplicationUser Contact { get; set; }
}

然后注册我的ApplicationUser和这个表之间的关系:

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

builder.Entity<UserContacts>()
            .HasOne(p => p.User)
            .WithMany(p => p.Contacts)
            .HasForeignKey(p => p.UserId);

在我的ApplicationUser类中添加了一个属性:

public virtual ICollection<UserContacts> Contacts { get; set; }

但每当我尝试更新数据库时,都会出现以下错误:

无法在&#39; ApplicationUser.Contacts&#39;之间建立关系。和&#39; UserContacts.User&#39;,因为&#39; ApplicationUser.Contacts&#39;之间存在关联。和&#39; UserContacts.Contact&#39;。导航属性只能参与一个关系。

你能告诉我我错过了什么吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您需要向ApplicationUser添加另一个集合:

public virtual ICollection<UserContacts> **Users** { get; set; }

然后将流畅的代码更改为指向那里(他们不能指向同一个集合):

builder.Entity<UserContacts>()
            .HasOne(p => p.User)
            .WithMany(p => **p.Users**)
            .HasForeignKey(p => p.UserId);