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

228
Vistas
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 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