Covers what N+1 queries are in EF Core, the code shapes that cause them, how to detect them with logging, Application Insights and MiniProfiler, and the fixes: projection, Include, batching by key and split queries.
N+1 means one query loads a list of N rows and then the code runs one more query per row to fetch related data: 1 + N round trips instead of 1 or 2. In EF Core it comes from lazy loading, a query inside a foreach (FirstOrDefaultAsync, CountAsync, Entry(x).Collection().Load()), or a mapper touching navigations. I detect it by counting SQL commands per request: EF Core logging (LogTo or the Microsoft.EntityFrameworkCore.Database.Command category), Application Insights dependency calls under one operation id, or MiniProfiler's duplicate-query warning. The fix is a set-based query: project with Select into a DTO, Include the navigation, or fetch the children in one query with Contains(ids) and join in memory. The trade-off: one round trip per request is the goal, but one huge joined query can cause cartesian explosion, so sometimes two queries beat one.
"N+1 is the most common EF Core performance bug I see. You run one query to get, say, 50 orders, and then for each order the code goes back to the database for its customer or its lines. That's 51 round trips. Each one is cheap on its own, maybe 1 to 2 milliseconds to Azure SQL in the same region, but they are sequential, so a page that should take 15 ms takes 300 ms, and it gets worse as the data grows. It also never shows up in a unit test with three rows.
In EF Core it comes from a few shapes: lazy loading proxies, where touching
order.Customersilently fires a query; anawait db.Something.FirstOrDefaultAsync()inside aforeach; callingEntry(x).Collection(...).LoadAsync()per item; or AutoMapper walking navigations. To find it I count commands per request. Locally I turn onLogToand see the same parameterised SELECT repeated. In production, Application Insights shows the end-to-end transaction with dozens of identical SQL dependency calls under one operation id, and MiniProfiler flags duplicate queries in development.The fix is to make it set-based. For read endpoints I project with
Selectinto a DTO, which EF Core translates into one query with joins or a correlated subquery. If I need entities, IIncludethe navigation. If the related data comes from a different query path, I collect the keys, run oneWhere(x => ids.Contains(x.Id))query, and stitch the results together with a dictionary. The mistake I see is fixing N+1 by Including everything, which turns 51 small queries into one query returning a cartesian product. The goal is a small, fixed number of queries per request, not necessarily one."
| Shape | Why it fires N queries | Fix |
|---|---|---|
| Lazy loading proxies | Every navigation access is a query | Turn lazy loading off; project or Include |
| Query inside a loop | await db.X.FirstOrDefaultAsync(...) per item |
One Contains(ids) query, then a dictionary |
| Explicit loading per item | Entry(e).Collection(c).LoadAsync() in a loop |
Include, or load all children in one query |
| Mapper or serialiser touching navigations | Triggers lazy loads during mapping | ProjectTo / manual Select before materialising |
| Count per row | db.Lines.CountAsync(l => l.OrderId == o.Id) in a loop |
Select(o => new { o.Id, LineCount = o.Lines.Count() }) |
| Tool | What you look for |
|---|---|
LogTo(Console.WriteLine, LogLevel.Information) or the Microsoft.EntityFrameworkCore.Database.Command log category |
The same SQL text repeated with different parameter values |
| Application Insights end-to-end transaction view | Dozens of identical SQL dependencies under one request; dependency count per request in a KQL query |
MiniProfiler (MiniProfiler.EntityFrameworkCore) |
Duplicate-query highlighting and total SQL time per request |
| An integration test with a command-counting interceptor | Fails the build when an endpoint exceeds its query budget |
An order history endpoint [in a system I worked on] loaded 100 orders and then lazily loaded each order's customer and shipping address: 201 queries and a p95 of about 900 ms. Replacing it with one Select projection cut it to a single query and a p95 of about 60 ms, and Azure SQL DTU use for that endpoint dropped by roughly two thirds.
Checks that the candidate can recognise N+1 from symptoms, knows the EF Core shapes that cause it, and fixes it with set-based queries without over-correcting.
Green flags
LogTo, Application Insights dependencies, MiniProfilerContains for key listsRed flags
DbContextEach query pays a fixed cost before any rows are read: a network round trip, SQL Server parsing or plan cache lookup, execution, and result materialisation in EF Core.
Request
├─ SELECT * FROM Orders WHERE CustomerId = @p (1 query, 100 rows)
├─ SELECT * FROM Customers WHERE Id = @p0 ┐
├─ SELECT * FROM Customers WHERE Id = @p0 │ 100 sequential
├─ ... │ round trips
└─ SELECT * FROM Customers WHERE Id = @p0 ┘
If one round trip costs 1.5 ms, 100 of them cost 150 ms of pure waiting, and they cannot run in parallel on one DbContext because a context does not support concurrent operations. Across regions (an app in Australia Southeast talking to a database in Australia East) the per-trip cost is higher still.
A projection lets EF Core translate the whole graph into one statement:
SELECT [o].[Id], [o].[PlacedAt], [c].[Name], (
SELECT COUNT(*) FROM [OrderLines] AS [l] WHERE [o].[Id] = [l].[OrderId]) AS [LineCount]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[CustomerId] = @customerId
For a key-list fetch, EF Core 8+ sends Contains over a parameter list as OPENJSON(@ids) on SQL Server (EF Core 10 adds more options for how the list is parameterised), so one query handles any number of keys with a stable plan.
Lazy loading proxies (UseLazyLoadingProxies()) override virtual navigation properties. The first access calls the context's lazy loader, which runs a query. The code looks like plain property access, so the cost is invisible in review. Serialising an entity graph to JSON touches every navigation, which turns one response into hundreds of queries. Most teams building APIs keep lazy loading off and make data access explicit.
Microsoft.EntityFrameworkCore.Database.Command. Group by SQL text to spot repeats.dependencies | where type == "SQL" | summarize count() by operation_Id finds requests with abnormal counts.DbCommandInterceptor that increments a counter lets an integration test assert Assert.True(counter.Count <= 3).The opposite failure is one query with several collection Includes. Each collection multiplies the row count, so 100 orders with 10 lines and 5 notes return 5,000 rows. The target is a small, bounded number of queries per request, whatever the data size.
order.Customer.Name with lazy loading on, and count the commands with LogTo.Select projection, print ToQueryString(), and compare timings with BenchmarkDotNet.DbCommandInterceptor that counts commands and fail an integration test when the count exceeds 2.Before and after: an N+1 loop replaced with one projection, plus a command-counting interceptor for tests.
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
public sealed record OrderSummary(int Id, DateTime PlacedAt, string CustomerName, int LineCount);
public sealed class OrderQueries(ShopDbContext db)
{
// BEFORE: 1 query for orders + 2 queries per order = 2N + 1 round trips.
public async Task<List<OrderSummary>> GetSlowAsync(int customerId, CancellationToken ct)
{
var orders = await db.Orders.Where(o => o.CustomerId == customerId).ToListAsync(ct);
var result = new List<OrderSummary>();
foreach (var o in orders)
{
var customer = await db.Customers.FirstAsync(c => c.Id == o.CustomerId, ct); // query per row
var lines = await db.OrderLines.CountAsync(l => l.OrderId == o.Id, ct); // and another
result.Add(new OrderSummary(o.Id, o.PlacedAt, customer.Name, lines));
}
return result;
}
// AFTER: one SQL statement with a join and a correlated COUNT subquery.
public Task<List<OrderSummary>> GetAsync(int customerId, CancellationToken ct) =>
db.Orders
.Where(o => o.CustomerId == customerId)
.Select(o => new OrderSummary(o.Id, o.PlacedAt, o.Customer.Name, o.Lines.Count))
.ToListAsync(ct);
// When the related rows come from elsewhere: one query by key list, then join in memory.
public async Task<Dictionary<int, string>> GetCustomerNamesAsync(IReadOnlyCollection<int> ids, CancellationToken ct) =>
await db.Customers
.Where(c => ids.Contains(c.Id)) // translated to OPENJSON / IN, one round trip
.ToDictionaryAsync(c => c.Id, c => c.Name, ct);
}
namespace Shop.Tests;
using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;
// Register with options.AddInterceptors(counter) in the test host, then assert a query budget.
public sealed class CommandCounter : DbCommandInterceptor
{
private int _count;
public int Count => _count;
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
Interlocked.Increment(ref _count);
return ValueTask.FromResult(result);
}
}
Include.Include for every navigation. Why it is wrong: several collection Includes in one query cause cartesian explosion. Instead: project only what the endpoint returns, or use AsSplitQuery() for multiple collections.Task.WhenAll on one DbContext. Why it is wrong: a DbContext is not thread-safe and throws on concurrent operations; even with separate contexts it multiplies load. Instead: replace N queries with one set-based query.IN list by string concatenation. Why it is wrong: SQL injection risk and a new plan per list length. Instead: use Contains on a collection, which EF Core parameterises.N+1 is a design smell more than a query bug: it appears when data access is hidden behind properties, repositories that return single entities, or mappers. The durable fix is to make each use case fetch its data in a known, bounded number of queries and to enforce that with a query budget in tests. I also review new endpoints by looking at the Application Insights dependency count, not just duration, because count is what grows with data.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
Select projection into a DTO |
Read endpoints | Least data, no tracking | When you need to modify and save the entities |
Include / ThenInclude |
Loading an aggregate to change it | Pulls full entities; tracked by default | Several collections at once (use split query) |
Contains(ids) then dictionary |
Related data from another context or service | Two round trips, simple | Very large key sets (batch them) |
AsSplitQuery() |
Multiple collection navigations | One query per collection | When you need a consistent snapshot without a transaction |
Both symptoms come from serialising lazy-loading entities. System.Text.Json reads every public property; each virtual navigation triggers a SQL query on first access (N+1), and back-references such as Order.Customer.Orders form a cycle, so the serialiser throws ("A possible object cycle was detected") or goes very deep.
I diagnose by counting SQL commands per request (EF Core command logging or Application Insights dependencies), then fix it properly: project to a DTO with Select so the response shape is explicit and EF Core sends one query, and turn lazy loading off (or make lazy loads throw) so it can't come back.
Setting ReferenceHandler.IgnoreCycles stops the exception but leaves the dozens of queries in place.
Cartesian explosion happens when one query Includes two or more sibling collections: SQL returns one row per combination, so an order with 50 lines and 20 payments becomes 1,000 rows, each repeating the order's columns. EF Core logs a warning when it sees this.
AsSplitQuery() makes EF Core send one root query plus one query per collection Include (orders; then lines joined to the same filtered orders; then payments) and stitch the results together in memory. For that order, rows transferred become 1 (root) + 50 (lines) + 20 (payments) = 71 instead of 1,000.
The trade-offs: an extra round trip per collection (it adds up with network latency), and the statements are not one consistent snapshot unless you wrap them in a transaction with snapshot isolation. Often the better answer is a projection that loads only what's needed.
For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.
Select are joined automatically; no Include is needed (and Include is ignored there).Include is still right when I load an aggregate to modify and save it, because I need tracked entities.The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.
How to tell it (STAR)
**S:** Our order history page in [the customer portal] went from about [120 ms] to [900 ms] at p95 after a release, and the database CPU climbed with it. **T:** I was asked to find the cause before the [end-of-month] traffic peak. **A:** In Application Insights I opened a slow request and saw about 200 near-identical SQL calls under one operation. Locally, EF Core logging showed lazy loading firing for every order's customer and address while the JSON serialiser walked the entities. I replaced the entity response with a DTO projection, which produced one query, turned lazy loading off for the API, and added an integration test that fails if the endpoint runs more than two queries. **R:** p95 dropped to around [60 ms], SQL load for that endpoint fell by roughly [two thirds], and the query-budget test has since caught [two] similar regressions in review.
Last updated 23 Nov 2026.