The N+1 query problem in EF Core occurs when an application sends one database query to retrieve a list, then executes another query for each item in that list. Loading 20 orders and fetching related information separately for each order can result in 21 database queries.

This behavior might go unnoticed with a small dataset. As the number of records and network latency increase, repeated database round trips become more expensive.

In this article, we reproduce the problem in a small application, inspect the generated SQL, and compare three loading approaches: Include, projection with Select, and AsSplitQuery.

What exactly is the N+1 query problem?

Suppose an orders page needs to display each order's ID and item count.

A straightforward implementation might look like this:

var orders = await db.Orders
    .OrderBy(o => o.Id)
    .ToListAsync();

foreach (var order in orders)
{
    var itemCount = await db.Items
        .CountAsync(i => i.OrderId == order.Id);

    Console.WriteLine($"Order {order.Id}: {itemCount} items");
}

The application first retrieves the orders. Each loop iteration then executes a separate command to count the items belonging to that order.

For this implementation:

Number of orders Initial list query Separate item-count queries Total SQL commands
3 1 3 4
20 1 20 21
100 1 100 101

The loop itself is not the problem. The problem is returning to the database separately for every item.

Does N+1 only happen with lazy loading?

Lazy loading is a common source of N+1 queries, but it is not the only one.

When lazy loading is configured, accessing an unloaded navigation property can execute a database query. An expression such as order.Items.Count might appear to read a property while actually fetching data behind the scenes.

The previous example creates N+1 queries without lazy loading because it explicitly calls CountAsync for each order.

The same pattern can hide inside repositories, helper services, or explicit relationship loading. Detecting it requires examining the commands actually sent to the database.

In EF Core, defining a navigation property does not automatically enable lazy loading. Proxy-based lazy loading, for example, requires its corresponding package and configuration.

Build a runnable example

We use an in-memory SQLite database so the example does not depend on an installed database server or existing data.

The following sample was run and checked with .NET 10 and EF Core 10.0.9.

Create a console application:

dotnet new console -n NPlusOneDemo --framework net10.0
cd NPlusOneDemo
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 10.0.9

Replace the contents of Program.cs with:

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

var orderCount = args.Length == 0 ? 3 : int.Parse(args[0]);

await using var connection =
    new SqliteConnection("Data Source=:memory:");

await connection.OpenAsync();

var setupOptions = new DbContextOptionsBuilder<ShopDb>()
    .UseSqlite(connection)
    .Options;

await using (var setup = new ShopDb(setupOptions))
{
    await setup.Database.EnsureCreatedAsync();

    for (var i = 1; i <= orderCount; i++)
    {
        setup.Orders.Add(new Order
        {
            Items = [new OrderItem(), new OrderItem()]
        });
    }

    await setup.SaveChangesAsync();
}

var commandCount = 0;

var options = new DbContextOptionsBuilder<ShopDb>()
    .UseSqlite(connection)
    .LogTo(message =>
    {
        commandCount++;
        Console.WriteLine(message);
    }, [RelationalEventId.CommandExecuted])
    .Options;

Console.WriteLine("=== N+1 ===");
commandCount = 0;

await using (var db = new ShopDb(options))
{
    var orders = await db.Orders
        .OrderBy(o => o.Id)
        .ToListAsync();

    foreach (var order in orders)
    {
        var itemCount = await db.Items
            .CountAsync(i => i.OrderId == order.Id);

        Console.WriteLine(
            $"Order {order.Id}: {itemCount} items");
    }
}

Console.WriteLine($"Commands: {commandCount}");

Console.WriteLine("=== Include ===");
commandCount = 0;

await using (var db = new ShopDb(options))
{
    var orders = await db.Orders
        .Include(o => o.Items)
        .AsSingleQuery()
        .OrderBy(o => o.Id)
        .ToListAsync();

    foreach (var order in orders)
    {
        Console.WriteLine(
            $"Order {order.Id}: {order.Items.Count} items");
    }
}

Console.WriteLine($"Commands: {commandCount}");

Console.WriteLine("=== Projection ===");
commandCount = 0;

await using (var db = new ShopDb(options))
{
    var rows = await db.Orders
        .OrderBy(o => o.Id)
        .Select(o => new
        {
            o.Id,
            ItemCount = o.Items.Count
        })
        .ToListAsync();

    foreach (var row in rows)
    {
        Console.WriteLine(
            $"Order {row.Id}: {row.ItemCount} items");
    }
}

Console.WriteLine($"Commands: {commandCount}");

Console.WriteLine("=== Split ===");
commandCount = 0;

await using (var db = new ShopDb(options))
{
    var orders = await db.Orders
        .Include(o => o.Items)
        .AsSplitQuery()
        .OrderBy(o => o.Id)
        .ToListAsync();

    foreach (var order in orders)
    {
        Console.WriteLine(
            $"Order {order.Id}: {order.Items.Count} items");
    }
}

Console.WriteLine($"Commands: {commandCount}");

public sealed class ShopDb(DbContextOptions<ShopDb> options)
    : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<OrderItem> Items => Set<OrderItem>();
}

public sealed class Order
{
    public int Id { get; set; }
    public List<OrderItem> Items { get; set; } = [];
}

public sealed class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; } = null!;
}

Run the application:

dotnet run

The application creates three orders with two items each, then executes the four loading approaches in sequence.

Each approach uses a fresh DbContext so previously loaded entities do not affect the comparison. The SQLite connection stays open to keep the in-memory database alive until the application finishes.

What are we measuring?

LogTo receives only the CommandExecuted event. Each successfully executed command prints a log entry and increments the counter.

Database creation and data insertion use separate configuration, so setup commands are excluded from the read counts.

The checked run with three orders produced these results:

Approach SQL commands Displayed result
Query inside the loop 4 Three orders with two items each
Include with a single query 1 Three orders with two items each
Select with database-side counting 1 Three orders with two items each
Include with a split query 2 Three orders with two items each

These numbers describe SQL command counts in this example. They do not establish how many times faster one approach will be in every application.

SQLite runs inside the application's process here. Response times with a remote database also depend on network latency, data volume, indexes, and server-side work.

What SQL does the N+1 version execute?

With timestamps and logging details removed, the first command is:

SELECT "o"."Id"
FROM "Orders" AS "o"
ORDER BY "o"."Id";

The following command then repeats for each order, using that order's ID as its parameter:

SELECT COUNT(*)
FROM "Items" AS "i"
WHERE "i"."OrderId" = @order_Id;

Each count query might be simple and fast individually. The problem is that its execution count grows with the number of orders.

A useful diagnostic signal is the same SQL shape appearing repeatedly with different parameters during one operation.

Fixing N+1 with Include

The second approach loads orders together with their items:

var orders = await db.Orders
    .Include(o => o.Items)
    .AsSingleQuery()
    .OrderBy(o => o.Id)
    .ToListAsync();

In this example, the generated SQL uses a LEFT JOIN:

SELECT "o"."Id", "i"."Id", "i"."OrderId"
FROM "Orders" AS "o"
LEFT JOIN "Items" AS "i"
    ON "o"."Id" = "i"."OrderId"
ORDER BY "o"."Id";

The items are loaded when the main query executes. Reading order.Items.Count in the subsequent loop counts the collection already in memory without issuing another database command.

We specify AsSingleQuery explicitly to make the comparison's query behavior clear.

However, a page that only needs an item count now loads all the item entities too. Removing N+1 does not necessarily mean we are retrieving only the required data.

Use Select when only a few values are needed

To display an order ID and item count, we can define the required result directly:

var rows = await db.Orders
    .OrderBy(o => o.Id)
    .Select(o => new
    {
        o.Id,
        ItemCount = o.Items.Count
    })
    .ToListAsync();

In this example, EF Core translates the count into SQL:

SELECT "o"."Id", (
    SELECT COUNT(*)
    FROM "Items" AS "i"
    WHERE "o"."Id" = "i"."OrderId"
) AS "ItemCount"
FROM "Orders" AS "o"
ORDER BY "o"."Id";

A subquery inside this SQL does not mean the application sends a separate request for each order. The application sends one command, and the database computes its result.

The database still performs work to calculate the counts, so query plans and indexes remain relevant. However, the repeated application-to-database round trips are removed, and item entities are not loaded.

Where the expression executes matters:

  • After ToListAsync, with the relationship loaded, order.Items.Count counts an in-memory collection.
  • Inside a translatable Select, the expression becomes part of the database query.

This projection does not require Include.

Why not add Include to every relationship?

Suppose we load both order items and payments as two sibling collections.

In a single query using JOINs, an order with six items and four payments can produce 24 combined rows. This is not the number of final order entities; it is the number of rows the JOIN combination can return.

This behavior is known as cartesian explosion. There is one SQL command, but it may transfer substantial duplicated data.

The smallest query count is therefore not the only goal. Data volume and processing costs also matter.

What does AsSplitQuery solve?

The fourth approach uses:

var orders = await db.Orders
    .Include(o => o.Items)
    .AsSplitQuery()
    .OrderBy(o => o.Id)
    .ToListAsync();

For this model with one collection navigation, two commands execute:

  1. Retrieve the orders.
  2. Retrieve the items related to those orders.

Unlike the N+1 implementation, the item-loading command is not repeated separately for every order.

Split queries can reduce row multiplication costs in certain queries that load multiple collections. The trade-off includes additional database round trips, and concurrent data changes can occur between the commands.

If all reads must observe a consistent state, the required guarantees and transaction strategy need consideration.

Adding AsSplitQuery to the original list query also does not rewrite the separate CountAsync calls inside the loop. The data-loading pattern must change first.

Does AsNoTracking fix N+1?

AsNoTracking changes entity tracking behavior. If the application still executes a separate CountAsync for every order, those database commands remain.

The projection in this article contains only an ID and a count. It does not return entity instances that require tracking.

These are separate questions:

  • How many database commands execute?
  • Which entities are tracked, and what does that cost?

No-tracking queries can be appropriate when loading entities that will not be modified, but they do not replace correcting an N+1 loading pattern.

How should we choose an approach?

Requirement Approach to consider Important consideration
IDs, counts, and a few display values Projection with Select Define the required data within the query.
Entity instances and a required relationship Include Check entity counts and the columns being loaded.
Multiple collections causing significant row multiplication AsSplitQuery Evaluate round trips and consistency requirements.
A separate lookup for each list item Rewrite the query or load data in batches Remove query-count growth tied to individual items.

This example contains only three orders. A real application should also control result size through appropriate filtering and pagination. Returning the entire dataset is not automatically efficient just because it takes one query.

This choice also relates to read-path design. As discussed in CQRS and separating read and write responsibilities, building a suitable display model does not necessarily require a second database. A focused projection against the existing database may be enough.

How can we detect the problem returning?

For an important path such as an orders list, examine behavior with different record counts. The sample accepts the number of orders as an argument:

dotnet run -- 20

For the implementation that queries inside the loop, the expected command count increases from four for three orders to 21 for twenty orders.

For the other three approaches in this example, command counts remain constant as the number of orders grows. Data volume and database work can still increase.

An integration test can also record database command counts for a particular operation. Counting must be scoped to that request or unit of work so concurrent operations do not contaminate the result.

Verify the output too. Reducing query counts is useful only if the required information is still returned correctly.

When investigating a slow path, this sequence helps:

  • Record the actual SQL and execution counts.
  • Identify repeated requests associated with individual list items.
  • Determine whether the page needs complete entities or only selected values.
  • Rewrite the query to match that requirement.
  • Check the result, command count, and data volume again.

The goal is data access that matches the operation's needs, without repeated round trips or unnecessary loading.