I am making a web application as a social network and I have a problem at the stage of creating models at EF Core (code-first, SQL Server).
I need to make the ability to add to friends for users. So, I am trying to establish a connection like "self referencing many-to-many". I saw how you can solve this problem by creating an additional array in the class, but is there any way to get around this "crutch"?
Here is my code of my User
class:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// ... Other properties
public ICollection<UserFriend> Friends { get; set; }
}
And this is the UserFriend
class:
public class UserFriend
{
public int UserId { get; set; }
public User User { get; set; }
public int FriendId { get; set; }
public User Friend { get; set; }
}
Also here is my DbContext
and its OnModelCreating
settings:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserFriend>()
.HasKey(i => new { i.UserId, i.FriendId });
modelBuilder.Entity<UserFriend>()
.HasOne(c => c.User)
.WithMany(w => w.UserFriends)
.HasForeignKey(f => f.UserId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserFriend>()
.HasOne(c => c.Friend)
.WithMany(w => w.UserFriends)
.HasForeignKey(f => f.FriendId)
.OnDelete(DeleteBehavior.Restrict);
}