2017-03-12 49 views
4

用户好友关系

一对多的关系我找到答案EF核心 - 许多对一类

Entity Framework Core: many-to-many relationship with same entity 和尝试这样的。

实体来说:

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'之间已经存在关系。 导航属性只能参与单个关系。

我该怎么办?或者我应该创建一个Entity FriendEntity:User?

回答

4

问题是你不能有一个集合来支持一对多关联。 Friend有两个外键,它们都需要在它们引用的实体中的反向结尾。因此,添加另一个集合为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); 

关系的一方(或双方)应不级联删除,以防止多个级联路径。

3

这不是强制性的第二个集合。你只需要留德.WithMany()清空这样的:

modelBuilder.Entity<Friend>() 
    .HasOne(f => f.MainUser) 
    .WithMany() 
    .HasForeignKey(f => f.MainUserId); 

modelBuilder.Entity<Friend>() 
    .HasOne(f => f.FriendUser) 
    .WithMany() 
    .HasForeignKey(f => f.FriendUserId); 

看看这个:https://github.com/aspnet/EntityFramework/issues/6052

+0

感谢,离开WithMany似乎已经解决了这个问题对我来说。 –

+0

尝试这样做会让我在数据库中留下额外的不必要的外键关系(我有三个,而不是两个,其中一个是多余的,但名称不同)。为了解决这个问题,我给WithMany()调用重新添加了一个参数:modelBuilder.Entity () .HasOne(f => f.FriendUser) .WithMany(mu => mu.MainUserFriends) 。 HasForeignKey(f => f.FriendUserId); – BernardV