I find an answer
Entity Framework Core: many-to-many relationship with same entity and try like this.
Entitys:
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 MainUserFriends { get; set; }
public virtual ICollection Friends { get; set; }
}
And the mapping:
modelBuilder.Entity()
.HasKey(f => new { f.MainUserId, f.FriendUserId });
modelBuilder.Entity()
.HasOne(f => f.MainUser)
.WithMany(mu => mu.MainUserFriends)
.HasForeignKey(f => f.MainUserId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity()
.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.