EF Core - Many to many relationship on a class

后端 未结 2 530
無奈伤痛
無奈伤痛 2020-12-18 06:07

User-Friend relationship

I find an answer

Entity Framework Core: many-to-many relationship with same entity and try like this.

Entitys:

         


        
相关标签:
2条回答
  • 2020-12-18 06:54

    It's not mandatory the second collection. You only need to left de .WithMany() empty like this:

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

    look at this : https://github.com/aspnet/EntityFramework/issues/6052

    0 讨论(0)
  • 2020-12-18 06:58

    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; }
    }
    

    And the mapping:

    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.

    0 讨论(0)
提交回复
热议问题