Efficiently Retrieving Buses and Awake Passengers in Entity Framework
This article addresses the challenge of retrieving buses and their awake passengers using Entity Framework (EF) in an efficient manner, minimizing database calls. The solution varies slightly depending on your EF version.
EF Core Versions Prior to 5:
Older EF versions require a workaround to achieve the desired result:
Disable Lazy Loading: Turn off lazy loading (Context.Configuration.LazyLoadingEnabled = false;
) to prevent unnecessary database hits when accessing related entities.
Projection Query: Use a projection query to select only the necessary data:
<code class="language-csharp">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>
Relationship Fixup (Automatic): EF's relationship fixup will automatically connect the selected AwakePassengers
to their respective buses in memory.
Mapping with AutoMapper (Optional): Use AutoMapper (or a similar library) to map the retrieved data to your DTOs.
Important Considerations (Pre-EF Core 5):
EF Core 5 and Later:
EF Core 5 and later versions offer a more elegant solution using IncludeWith(...)
:
<code class="language-csharp">var buses = Context.Busses.Where(b => b.IsDriving) .Include(b => b.Passengers.Where(p => p.Awake)) .ToList();</code>
This single query efficiently retrieves buses and only their awake passengers, eliminating the need for the workaround in earlier versions. Direct mapping to DTOs using AutoMapper can then be applied.
This improved approach in EF Core 5 provides a cleaner and more efficient method for retrieving related entities with filtering, significantly simplifying the process.
The above is the detailed content of How Can I Efficiently Retrieve Buses and Their Awake Passengers in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!