问题描述
我找到了答案
实体框架核心:多对多与同一实体的关系并像这样尝试.
实体:
public class User
{
public int UserId { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
public class Friend
{
public int MainUserId { get; set; }
public User ManUser { get; set; }
public int FriendUserId { get; set; }
public User FriendUser { get; set; }
}
流畅的 API:
modelBuilder.Entity<Friend>()
.HasKey(f => new { f.MainUserId, f.FriendUserId });
modelBuilder.Entity<Friend>()
.HasOne(f => f.ManUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.MainUserId);
modelBuilder.Entity<Friend>()
.HasOne(f => f.FriendUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.FriendUserId);
当我添加迁移时,错误信息是
无法在User.Friends"和Friend.FriendUser"之间创建关系,因为User.Friends"和Friend.ManUser"之间已经存在关系.导航属性只能参与一个关系.
When I Add-Migration, the error message is
Cannot create a relationship between 'User.Friends' and 'Friend.FriendUser', because there already is a relationship between 'User.Friends' and 'Friend.ManUser'.Navigation properties can only participate in a single relationship.
我该怎么办?或者我应该创建一个实体 FriendEntity:User?
What should I do? Or I should create an Entity FriendEntity:User?
推荐答案
问题是你不能让一个集合同时支持一对多的关联.Friend
有两个外键,它们都需要在它们引用的实体中有一个反向.所以添加另一个集合作为 MainUser
的反面:
The problem is that you can't have one collection to support both one-to-many associations. Friend
has two foreign keys that both need an inverse end in the entity they refer to. So add another collection as inverse end of MainUser
:
public class User
{
public int UserId { get; set; }
public virtual ICollection<Friend> MainUserFriends { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
和映射:
modelBuilder.Entity<Friend>()
.HasKey(f => new { f.MainUserId, f.FriendUserId });
modelBuilder.Entity<Friend>()
.HasOne(f => f.MainUser)
.WithMany(mu => mu.MainUserFriends)
.HasForeignKey(f => f.MainUserId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Friend>()
.HasOne(f => f.FriendUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.FriendUserId);
其中一个(或两个)关系应该没有级联删除,以防止多个级联路径.
One (or both) of the relationships should be without cascading delete to prevent multiple cascade paths.
这篇关于EF Core - 类上的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!