This inspection reports situations where a query is performed over a set of entities (for example, with the DbSet<T>.AsAsyncEnumerable() method), and related entities are accessed within the query without being eagerly loaded or explicitly included in the query.
When this happens, the related entities may not be loaded into memory, leading to incomplete or missing data for those entities. This can result in unexpected behavior or errors further down the line.
To avoid this problem, you can either eagerly load related entities using the Include() method or enable lazy loading, so that related entities are loaded on-demand when they are accessed.
Suboptimal code
awaitforeach(var person in ctx.People.AsAsyncEnumerable())
{
// do something
foreach(var account in person.Accounts)
{
result.Append(account.Login);
}
}
After the quick-fix
awaitforeach(var person in ctx.People.Include(person
=> person.Accounts).AsAsyncEnumerable())
{
// do something
foreach(var account in person.Accounts)
{
result.Append(account.Login);
}
}
In the above example, the code is using AsAsyncEnumerable() to asynchronously iterate over the PeopleDbSet, but it is not including any eager loading of the Accounts navigation property of each Person entity.
Since the iteration is performed asynchronously, the context may be disposed or modified before the nested foreach loop can be executed, causing the Accounts collection to be incomplete or even empty for some Person entities.
To fix the issue, we use the Include() method to eagerly load the Accounts navigation property for each Person entity.
note
Using multi-level Include/ThenInclude calls may lead to a cartesian explosion (depending on your database configuration). You may want to consider adding the AsSplitQuery() method to your query when using Entity Framework Core.
Our website uses some cookies and records your IP address for the purposes of accessibility, security, and managing your access to the telecommunication network. You can disable data collection and cookies by changing your browser settings, but it may affect how this website functions. Learn more.
With your consent, JetBrains may also use cookies and your IP address to collect individual statistics and provide you with personalized offers and ads subject to the Privacy Notice and the Terms of Use. JetBrains may use third-party services for this purpose. You can adjust or withdraw your consent at any time by visiting the Opt-Out page.