2017-03-12 50 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