Skip to main content
2 of 2
edited body; added 302 characters in body
Nick Muller
  • 2.3k
  • 3
  • 23
  • 46

Entity Framework Core: How do I ensure a navigation property is loaded?

Say I have the following models:

public class Subject { private List<SubjectResponse> responses; public int Id { get; private set; } public IEnumerable<SubjectResponse> Responses => responses.ToList(); public void Foo() { // How do I check here if Responses fully has been loaded? foreach (var response in Responses) { // ... } } } public class SubjectResponse { public int Id { get; private set; } } 

How do I check if all responses have been loaded in Foo()? I'd probably check for if (Responses is null), but that won't work in all cases.

Here is a minimum example of what could do wrong. In a real app the responses could be loaded at a completely different place. But h This shows how the responses could be fixed up by EF, so it could contain entries, but not all entries.

public async Task Bar() { var response = await dbContext.SubjectResponses.SingleAsync(s => s.Id == 1); var subject = await dbContext.Subjects.SingleAsync(s => s.Id == 1); subject.Foo(); // subject.Responses now has a count if 1, when there might actually be more responses. } 

I don't want to use lazy loading, because of performance implications (and because Lazy Loading won't load related entities async). Eager and Explicit loading are fine.

Edit: what I’m mainly looking for is a way to check if the navigation property has been loaded fully, so that I can load it it has not been.

Nick Muller
  • 2.3k
  • 3
  • 23
  • 46