
Beyond Include: Fixing N+1 in EF Core With Projections and Split Queries
- كاتب موثّق
- EF Core 10
محتويات المقال
Include calls, and the log drops to a single command, plus a warning nobody reads. That one command returned 1,500 rows of 17 columns and tracked 730 entities, to build 50 summaries of four values each.
The common misconception
Include problem. Include every navigation the code touches, and data access is fixed.
Include really does remove the extra round trips, and Microsoft's own performance guide says to load related entities eagerly when you know you'll need them. The number most people watch, queries per request, goes from 111 to 1. And on a development database with three orders, the new query is fast.
What actually happens
Where the N+1 comes from
foreach that queries or calls Load() per item does the same thing. Microsoft's docs warn that lazy loading makes N+1 very easy to trigger and recommend avoiding it.
Include loads entities, not answers
Include tells EF Core to bring whole entities for each navigation: every mapped column, tracked by default. The list page needed an order id, a customer name, a total and a payment count. The included query in the test returned 17 columns, including a 500-character product description that the page never shows, and left 730 entities in the change tracker.
Two collections multiply rows
MultipleCollectionIncludeWarning whenever a query loads more than one collection without a configured splitting behavior.
A projection asks for the answer
Select describes the result instead of the entities. EF Core translates the whole shape, including Sum and Count over collections, into SQL, so the database computes the totals and returns one row per order. In the test, the projected query returned 50 rows of 4 columns and tracked nothing. Include has no role here: in the test, adding it to a query that projects into a DTO changed nothing in the SQL.
The fix: project the read
using Microsoft.EntityFrameworkCore;public sealed class OrderSummaries(ShopDb db){ public async Task<List<OrderSummary>> ListAsync( DateTime since, CancellationToken ct) { // One query instead of 111, but whole entities from five tables var orders = await db.Orders .Include(o => o.Customer) .Include(o => o.Lines).ThenInclude(l => l.Product) .Include(o => o.Payments) .Where(o => o.PlacedAt >= since) .ToListAsync(ct); // tested: 1,500 rows, 17 columns, 730 tracked return orders.Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Lines.Sum(l => l.Quantity * l.UnitPrice), o.Payments.Count)).ToList(); }}using Microsoft.EntityFrameworkCore;public sealed class OrderSummaries(ShopDb db){ public Task<List<OrderSummary>> ListAsync( DateTime since, CancellationToken ct) => db.Orders .Where(o => o.PlacedAt >= since) // Sum and Count run in SQL: one row per order, four columns .Select(o => new OrderSummary( o.Id, o.Customer.Name, o.Lines.Sum(l => l.Quantity * l.UnitPrice), o.Payments.Count)) .ToListAsync(ct); // tested: 50 rows, nothing tracked}When you need the collections themselves
using Microsoft.EntityFrameworkCore;public sealed class OrderDetailsQuery(ShopDb db){ public Task<OrderDetails> GetAsync(int id, CancellationToken ct) => db.Orders.Where(o => o.Id == id) .Select(o => new OrderDetails(o.Id, o.Customer.Name, o.Lines.Select(l => new LineDto(l.Product.Name, l.Quantity)) .ToList(), o.Payments.Select(p => new PaymentDto(p.Amount, p.PaidAt)) .ToList())) // One SQL query per collection instead of lines × payments rows .AsSplitQuery() .SingleAsync(ct);}AsSplitQuery with all four Include calls brought 1,500 rows down to 700 across three commands, but still tracked all 730 entities.
Include everything | |||
Include + AsSplitQuery | |||
Select |
How to apply it in your project
Count the commands per request Turn on command logging and look for two shapes: the same SELECTrepeated with a different key (N+1), and one statement with severalLEFT JOINs to collections (explosion).Turn off lazy loading on read paths Remove UseLazyLoadingProxies, or at least keep proxied entities out of mappers and serializers, where navigation access is invisible.Project read endpoints Selectinto the DTO the response needs and letCount,Sumand other aggregates run in SQL. DropIncludefrom queries that project into DTOs; it has no effect there.Split only where collections multiply Use AsSplitQueryon queries that load two or more collections, or setUseQuerySplittingBehaviorglobally and opt out withAsSingleQuery.
Key takeaways
N+1 is a round-trip problem: related data loaded per row through lazy loading, Load()or queries inside loops.Includefixes the round trips but loads whole tracked entities, and two collections multiply rows: 1,500 for 50 orders in the test.For reads, project into exactly what the response needs; aggregates run in the database and nothing is tracked. Includedoes nothing in a query that projects into a DTO, so don't combine them.When you need several collections, use AsSplitQueryand accept its trade-offs: extra round trips and no single snapshot.
التعليقات (0)