Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

324
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda