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

270
Visualizações
EF core configuration for self referencing list

I'm having some trouble trying to configure some entity with self reference. My entities looks pretty much like the following:

public class MainEntity 
{
  public Guid Id {get; private set;}
  ...
  public IReadOnlyList<Foo> Foos => _foos;
  private readonly List<Foo> _foos {get; private set;} = new List<Foo>();
}
public class Foo
{
  public Guid Id {get; private set;}
  public Guid MainEntityId {get; private set;}

  public IReadOnlyList<Bar> Bars => _bars;
  private readonly List<Bar> _bars {get; private set;} = new List<Bar>();
  
}
public class Bar
{
  public Guid Id {get; private set;}
  public Guid? FooId {get; private set;}
  public Guid? ParentBarId {get; private set;}

  public IReadOnlyList<Bar> Bars => _bars;
  private readonly List<Bar> _bars {get; private set;} = new List<Bar>();  
}

So basically the MainEntity has list of Foos which has list of Bars with possible inner Bars list (you can look at MainEntity as some user profile; Fools as list of user posts; Bars as comments of a post or replays of some parent comment)

Initially I thought everything was fine, but later noticed that by doing context.MainEntities.Include(x => x.Foos).ThenInclude(x => x.Bars).First(); I only get first layer of Bars (that has FooId) and somebar.Bars is always empty.

I could use ThenInclude(x => x.Bars) multiple times but that doesn't really make sense since max depth isn't limited and would hurt a retrieval performance.

I tried having Bar.FooId ar not nullable and populate it but had no luck (context.SaveChangesAsync() couldn't resolve the relationship, probably because of missconfiguration in modelbuilder). Also im not sure if it won't cause additional issues like Foo containing all of Bars with FooId even tho Bar has ParentBar...

Sometimes my explanations can be confusing, so let me know if any clarification is needed.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

So, the solution is very simple. Firstly I will demonstrate the way I modified the entities:

public class MainEntity
{
   public Guid Id { get; set; }

   public string Name { get; set; }

   public IReadOnlyList<Foo> Foos { get; set; }
}

public class Foo
{
   public Guid Id { get; set; }

   public string Name { get; set; }

   public Guid MainEntityId { get; set; }

   public IReadOnlyList<Bar> Bars { get; set; }
}

public class Bar
{
   public Guid Id { get; set; }

   public string Name { get; set; }

   public Guid? FooId { get; set; }

   public Guid? ParentBarId { get; set; }

   public virtual Bar ParentBar { get; set; } 
   public virtual ICollection<Bar> ChildrenBars { get; set; }
}

As you can see, I also added ParentBar field, that has a type of Bar.

Next step is to ovveride the OnModelCreating method in your AppDbContext class as depicted below:

...

public DbSet<MainEntity> MainEntities { get; set; }

public DbSet<Foo> Foos { get; set; }

public DbSet<Bar> Bars { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Bar>()
           .HasMany(b => b.ChildrenBars)
           .WithOne(b=>b.ParentBar)
           .HasForeignKey(b=>b.ParentBarId);    
}

And finally, in your controller, you can call the MainEntites like next:

return await _context.MainEntities.Include(me=>me.Foos)
            .ThenInclude(me=>me.Bars).ToListAsync();

This, will return you a response as shown below:

api response

I hope my answer was useful and helpful!

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