EF核心-课堂上的多对多关系 [英] EF Core - Many to many relationship on a class
问题描述
我找到了答案
实体框架核心:多对多与同一实体的关系 并尝试这样.
实体:
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.
我该怎么办?还是我应该创建一个Entity 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核心-课堂上的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!