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

227
Visualizações
EF Core relationship collection .Count() vs .Count

I have a primary entity that contains a collection of related entities (one-to-many). The following is a simplified code example of my scenario:

class Secondary {}

class Primary {
  private readonly List<Secondary> _secondaries = new();
  public IReadOnlyList<Secondary> Secondaries => _secondaries;
}

In my EF repository i'm trying to project Primary into a DTO which contains a COUNT of Secondary entries in its collection:

DbContext.Set<Primary>()
    .AsNoTracking()
    .Select(primary => new PrimaryDTO{
        SecondaryCount = primary.Secondaries.Count // Access the Count property
    });

This query produces an exception: "Object reference not set to an instance of an object." But if i do this instead:

DbContext.Set<Primary>()
    .AsNoTracking()
    .Select(primary => new PrimaryDTO{
        SecondaryCount = primary.Secondaries.Count() // Call the Count() method
    });

The query works fine. But my IDE says that i should be accessing the property instead of calling the method, and shows the parenthesis next to the Count() call in gray, as if they're redundant. If i follow those instructions my code breaks.

How can one produce a null exception while the other doesn't? Also how can primary.Secondaries be null at all if my class initializes it as an empty list? FYI Using Include() to load the related collection doesn't alter this behavior.

over 4 years ago · Santiago Trujillo
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