JetBrains Rider 2023.1 Help

Code Inspection: Query can return incomplete data for related entities

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.

await foreach (var person in ctx.People.AsAsyncEnumerable()) { // do something foreach (var account in person.Accounts) { result.Append(account.Login); } }
await foreach (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 People DbSet, 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.

Last modified: 12 May 2023