Enable throwing when accessing non-included property when eager loading

Open
#25,818 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
csharp, sql
Domain
backend, database

Research direction

Start by reading ConfigureWarnings and CoreEventId.NavigationLazyLoading, then trace how eager-loading Include and ThenInclude behave with the SQL Server provider. Define the warning or throw behavior for accessing properties not included, using the contrasting examples in the issue to verify what completion should mean.

Written by the indexing model from the issue text.

Description

area-change-tracking area-query customer-reported

Is there a way to configure EF via ConfigureWarnings or some other mechanism to throw or show warnings when attempting to use a property that's not loaded via include call when using eager loading? Something like CoreEventId.NavigationLazyLoading but for Eager loaded properties?

Something like

var foo = dbContext.Foo.Include(x => x.Bar).First();
var prop = foo.NestedProperty;
// throws

var foo = dbContext.Foo.Include(x => x.Bar).Include(x => x.NestedProperty).First();
var prop = foo.NestedProperty;
// OK
Reasoning

I've inherited a pretty convoluted DB model that I don't control where having this would cut QA massively, basically some models have collections which may be replaced with collections from a related property if certain props are null, trivial example(usually we don't depend only on a single property):

var result = dbContext.Entities
        .Include(x => x.RelatedEntity)
        .ThenInclude(x => x.EntityCollection)
        .Include(x => x.EntityCollection);

if(result.RelatedEntity != null) {
        result.EntityCollection = result.RelatedEntity.EntityCollection
}

Due to the team size(and entity size) this has been causing issues long term and forcing us to add bunch of business logic and validation into the domain objects while it could be trivialized with Automapper or a similar library if we had the guarantee that the model was loaded correctly.

EF Core version:
Database provider: (Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (.NET 5.0/.NET Core 3.1)

Dominant language
C#
Stars
14.8k
Forks
3.4k
Avg merge
2d 5h
Merged PRs (30d)
134

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.