Lor*_*ill 19 c# linq entity-framework-core .net-core asp.net-core
我试图映射与同一实体的多对多关系.该User
实体有一个IList<User>
数据字段Contacts
,用于存储用户的联系人/朋友信息:
public class User : DomainModel
{
public virtual IList<User> Contacts { get; protected set; }
//irrelevant code omitted
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用流畅的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
Run Code Online (Sandbox Code Playgroud)
那么为什么会这样呢?有没有什么我做错了映射这种多对多的关系?
smo*_*nes 23
那么为什么会这样呢?有没有什么我做错了映射这种多对多的关系?
尚不支持没有实体类来表示连接表的多对多关系.但是,您可以通过包含连接表的实体类并映射两个单独的一对多关系来表示多对多关系.
使用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<UserContacts> Contacts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
而你的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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13019 次 |
最近记录: |