2

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);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Maxim
  • 21
  • 1
  • What so bad to have the public ICollection Friends { get; set; } in your class? – Roman Aug 30 '21 at 23:03
  • That's does not work, because you need to set up relationships between tables and it turns out that we have a self-referencing many-to-many relationship – Maxim Sep 02 '21 at 18:12
  • https://stackoverflow.com/questions/5125052/self-referencing-many-to-many-recursive-relationship-code-first-entity-framework ? – Roman Sep 03 '21 at 21:22
  • This method does not work in EF Core – Maxim Sep 04 '21 at 12:51

1 Answers1

0

Your collection in User should be of the type Friend and not UserFriend. Also make it virtual:

public virtual ICollection<Friend> Friends {get;set;}
GH DevOps
  • 305
  • 1
  • 11
  • sorry, I made a mistake with the name "Friends", but with the indication the virtual does not work anyway. – Maxim Aug 30 '21 at 18:35