الانتقال إلى المحتوى
.NETEF Core· 7 دقائق للقراءة

Beyond Include: Fixing N+1 in EF Core With Projections and Split Queries

Include turns many round trips into one, but that one query can carry every column of every table, multiplied. Projections ask the database for the answer instead.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

An order list endpoint is slow, and the SQL log shows why: one query for the orders, then one per order for its lines, one per order for its payments, and one per customer. In a test with EF Core 10 and SQLite, a page of 50 orders took 111 commands. The fix in the pull request adds four 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

The belief: N+1 is a missing-Include problem. Include every navigation the code touches, and data access is fixed.

There's a lot of truth in it. 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.

The catch: the number of queries is only one cost. The other is what each query brings back.

What actually happens

Where the N+1 comes from

The extra queries appear whenever related data is loaded per row. With lazy loading proxies, every first access to a navigation runs its own query. In the test, mapping 50 orders to summaries ran 1 query for the orders, 50 for lines, 50 for payments and 10 for customers, one per distinct customer, since the change tracker reused customers it had already loaded. A 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

When a single SQL query joins a parent to two collections at the same level, the database returns every combination: each line paired with each payment. That's a . Ten lines and three payments make 30 rows per order, so 50 orders came back as 1,500 rows. EF Core knows this is risky: it logs 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

C#
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();    }}

Both versions send one query. The difference is what crosses the wire: the right one asks the database for the four values the page shows and lets it do the arithmetic.

When you need the collections themselves

A detail page does need the lines and the payments. A projection still keeps the columns down, but two collections in one query still multiply: in the test, one order came back as 30 rows. A loads each collection with its own SQL statement instead:

C# OrderDetailsQuery.cs
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);}

In the test, this ran three commands: the order with its customer, the lines with product names, and the payments. Applied to the original list, AsSplitQuery with all four Include calls brought 1,500 rows down to 700 across three commands, but still tracked all 730 entities.

Approach (50 orders, tested)CommandsWhat comes backTracked
Lazy loading111Whole entities, one navigation at a time710
Include everything11,500 rows × 17 columns730
Include + AsSplitQuery3700 rows of whole entities730
Projection with Select150 rows × 4 columns0

How to apply it in your project

  1. Count the commands per requestTurn on command logging and look for two shapes: the same SELECT repeated with a different key (N+1), and one statement with several LEFT JOINs to collections (explosion).
  2. Turn off lazy loading on read pathsRemove UseLazyLoadingProxies, or at least keep proxied entities out of mappers and serializers, where navigation access is invisible.
  3. Project read endpointsSelect into the DTO the response needs and let Count, Sum and other aggregates run in SQL. Drop Include from queries that project into DTOs; it has no effect there.
  4. Split only where collections multiplyUse AsSplitQuery on queries that load two or more collections, or set UseQuerySplittingBehavior globally and opt out with AsSingleQuery.

Key takeaways

  • N+1 is a round-trip problem: related data loaded per row through lazy loading, Load() or queries inside loops.
  • Include fixes 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.
  • Include does nothing in a query that projects into a DTO, so don't combine them.
  • When you need several collections, use AsSplitQuery and accept its trade-offs: extra round trips and no single snapshot.

📚 المصادر

  1. Efficient Querying — EF Core, Microsoft Learn
  2. Single vs. Split Queries — EF Core, Microsoft Learn
  3. Loading Related Data — EF Core, Microsoft Learn
  4. Lazy Loading of Related Data — EF Core, Microsoft Learn

التعليقات (0)