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.