Optimizing EF Queries: Filtering Related Entities with Include
This article addresses the challenge of efficiently retrieving related entities with a Where
clause within an Entity Framework (EF) query. The goal is to avoid multiple database trips.
The scenario involves two entities: Bus
and Person
, with Bus
having a collection navigation property for Person
. The objective is to retrieve all buses that are driving, along with only those passengers who are awake.
A common inefficient approach results in multiple database calls. A more efficient solution involves disabling lazy loading and explicitly loading related entities with a filtered Where
clause within the query.
Here's an example demonstrating this approach:
<code class="language-csharp">Context.Configuration.LazyLoadingEnabled = false; var buses = Context.Busses.Where(b => b.IsDriving) .Select(b => new { Bus = b, AwakePassengers = b.Passengers.Where(p => p.Awake) }) .AsEnumerable() .Select(x => x.Bus) .ToList();</code>
This code first retrieves driving buses and their awake passengers in a single database query. The AsEnumerable()
call materializes the results in memory, allowing EF to correctly establish the relationships. Finally, only the Bus
objects are selected and returned.
Important Considerations:
This method, while effective in EF6, might require adjustments for many-to-many relationships and in EF Core. EF Core offers features like global query filters that can provide alternative solutions for more complex scenarios. For detailed information on these advanced techniques and handling many-to-many relationships, please refer to the original source.
The above is the detailed content of How Can I Efficiently Include Related Entities with a Where Clause in an EF Query?. For more information, please follow other related articles on the PHP Chinese website!