实体框架核心:与同一实体的多对多关系 [英] Entity Framework Core: many-to-many relationship with same entity
问题描述
我正在尝试将多对多关系与同一个实体进行映射。 用户
实体具有 IList< User>
数据字段联系人
,它存储用户的联系人/朋友信息:
I am trying to map many-to-many relationship with the same entity. The User
entity has an IList<User>
data field for Contacts
, which stores user's contacts/friends information:
public class User : DomainModel
{
public virtual IList<User> Contacts { get; protected set; }
//irrelevant code omitted
}
当我尝试使用流利的API映射这么多关系很多,给我一些麻烦。显然,当我在 user.Contacts
属性中使用 HasMany()
时,它没有 WithMany()
方法调用next。 Visual Studio中的智能感知器只显示 WithOne()
,但不显示 WithMany()
。
When I try to use fluent API to map this many to many relationship, it gives me some trouble. Apparently, when I use HasMany()
on the user.Contacts
property, it has no WithMany()
method to call next. The intellisense from Visual Studio only shows WithOne()
, but not 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
那么为什么会这样呢?是否有任何错误的地图映射这种多对多的关系?请帮忙。
So why does this happen? Is there anything I did wrong to map this many-to-many relationship? Please help.
推荐答案
那么为什么会发生这种情况?有没有什么我做错的地图这个
多对多关系?
So why does this happen? Is there anything I did wrong to map this many-to-many relationship?
No, you didn't do anything wrong. It's just not supported. Current status here.
尚未支持没有实体类来表示
连接表的多对多关系。然而,您可以通过为连接
表包含一个实体类来映射两个单独的一对多关系来代表
多对多关系。
Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.
使用EF-Core,您应该为映射表创建实体。例如 UserContacts
。 docs 中的完整示例,作为在评论中提到。我没有实际测试下面的代码,但它应该看起来像这样:
With EF-Core you should create the entity for the mapping table. Such as UserContacts
. A complete example in the docs, as mentioned in the comments. I haven't actually tested the code below, but it should look something like this:
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);
这篇关于实体框架核心:与同一实体的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!