Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

335
Views
How to implement a self-referencing many-to-many relations in .NET EF Core

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);
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

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;}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!