Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

331
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda