Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!