Introduction
In an ASP.NET Core application, a query can return correct results and still be inefficient. This is especially common when related data is loaded from a relational database. The most familiar example is the N+1 problem.
With an N+1 problem, the application first executes one query to retrieve a set of principal records. It then executes another query for each principal record in order to load related data. For example, an endpoint may retrieve 100 products with one query and then issue 100 additional queries to read their categories or order items. The total becomes 101 database queries. As the number of records increases, network latency, database CPU usage, connection activity, and API response time also increase.
In this lesson, we will use product, category, and order relationships to create and identify an N+1 problem. We will then compare several loading strategies. The goal is not to force every scenario into a single SQL query. The goal is to select a loading strategy that is explicit, appropriate for the data shape, and verified with measurements.
1. Sample data model
In the following model, each product belongs to a category, an order contains multiple order items, and each order item points to a product.
public class Category
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public ICollection<Product> Products { get; set; } = new List<Product>();
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public decimal Price { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; } = null!;
public ICollection<OrderItem> OrderItems { get; set; } = new List<OrderItem>();
}
public class Order
{
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public ICollection<OrderItem> Items { get; set; } = new List<OrderItem>();
}
public class OrderItem
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public Order Order { get; set; } = null!;
public Product Product { get; set; } = null!;
}For read-only scenarios, queries should select only the fields required by the endpoint. The AsNoTracking and projection techniques discussed in the previous lesson remain important here. Loading related entities is only part of the problem; avoiding unnecessary columns and objects is also essential.
2. Creating the N+1 problem
When lazy loading is enabled, the following code may look harmless:
var products = await db.Products.ToListAsync();
foreach (var product in products)
{
Console.WriteLine($"{product.Name} - {product.Category.Name}");
}The first line sends a query to retrieve the products. When product.Category.Name is accessed, EF Core may send another query if the category has not already been loaded. With 100 products, a large number of additional queries can be generated, even when several products belong to the same category.
The same pattern can occur with orders:
var orders = await db.Orders.ToListAsync();
foreach (var order in orders)
{
foreach (var item in order.Items)
{
Console.WriteLine($"{item.Product.Name}: {item.Quantity}");
}
}Depending on the configured loading behavior, the application may query the orders first, then query the items for each order, and finally query the product for each item. The query count is no longer obvious from the first line of code. It depends on how many navigation properties are accessed during iteration.
3. Detecting the problem
Measure the problem before changing the implementation. During development, EF Core command logging can be enabled at the Information level:
builder.Services.AddDbContext<StoreDbContext>(options =>
options.UseSqlServer(connectionString)
.LogTo(Console.WriteLine, LogLevel.Information));If one request produces many structurally similar SELECT statements, an N+1 problem is likely. A changing parameter such as WHERE CategoryId = ... or WHERE OrderId = ... on every statement is a useful indicator.
During development, you can also inspect the SQL representation of an IQueryable with ToQueryString():
var query = db.Products
.Where(p => p.Price > 100)
.Include(p => p.Category);
var sql = query.ToQueryString();
Console.WriteLine(sql);Logging should capture more than the final API duration. For a useful comparison, record:
- Total database command count
- Total SQL execution time
- Total API response time
- Number of principal and related records returned
- Response payload size
EF Core logs and diagnostic events can help identify when commands are executed. In production, avoid exposing sensitive parameter values and enable detailed SQL logging only with an appropriate operational policy.
4. Controlled loading with eager loading
When related data is definitely required, use eager loading. The Include and ThenInclude methods make the loading plan explicit in the query.
var products = await db.Products
.AsNoTracking()
.Include(p => p.Category)
.Where(p => p.IsActive)
.ToListAsync();This approach does not hide additional database calls in property access. However, adding multiple collection navigations can create large JOIN statements and repeated rows. For example, loading several collection relationships for the same order can produce a result where the order columns are repeated for combinations of related rows.
Keep the relationship graph limited to what the endpoint actually needs:
var orders = await db.Orders
.AsNoTracking()
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.ThenInclude(p => p.Category)
.Where(o => o.CreatedAt >= startDate)
.ToListAsync();This query is clear and predictable, but it can still materialize a large entity graph. For list endpoints, projection is often a better fit because the API usually needs a small result shape rather than complete entity objects.
5. Producing focused results with projection
Projection selects the fields required by the endpoint instead of materializing complete entities. This can reduce the number of transferred columns and the cost of creating objects.
var result = await db.Products
.AsNoTracking()
.Where(p => p.IsActive)
.Select(p => new ProductListItemDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
CategoryName = p.Category.Name
})
.ToListAsync();EF Core can translate p.Category.Name into the required SQL relationship operation. The category entity does not need to be materialized as a separate object when the endpoint only needs its name.
An order summary can use the same strategy:
var summaries = await db.Orders
.AsNoTracking()
.Where(o => o.CreatedAt >= startDate)
.Select(o => new OrderSummaryDto
{
Id = o.Id,
CreatedAt = o.CreatedAt,
ItemCount = o.Items.Count(),
Total = o.Items.Sum(i => i.Quantity * i.Product.Price),
Items = o.Items.Select(i => new OrderItemDto
{
ProductId = i.ProductId,
ProductName = i.Product.Name,
Quantity = i.Quantity,
UnitPrice = i.Product.Price
}).ToList()
})
.ToListAsync();This produces a result shaped for the API or user interface. Nevertheless, the generated SQL should still be inspected, and pagination should be applied when the result set can become large.
6. When to use split queries
In many cases EF Core uses a single-query approach for related data. When several collection navigations are loaded together, JOIN results may repeat principal columns many times. This is often called a cartesian explosion or data duplication problem.
For such a query, you can request split-query behavior:
var orders = await db.Orders
.AsNoTracking()
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.AsSplitQuery()
.Where(o => o.CreatedAt >= startDate)
.ToListAsync();A split query loads collection relationships through separate SQL statements. This can reduce repeated data caused by a large JOIN and can produce smaller intermediate result sets. It also has costs: each query may require another database round trip, the data can change between statements, and some results may need to remain buffered in memory.
When using Skip and Take with split queries, make the ordering fully unique. Instead of sorting only by a timestamp, combine it with a unique key:
var orders = await db.Orders
.OrderByDescending(o => o.CreatedAt)
.ThenByDescending(o => o.Id)
.Skip(offset)
.Take(pageSize)
.AsSplitQuery()
.Include(o => o.Items)
.ToListAsync();The better option depends on data volume, network latency, relationship count, and the database execution plan. Always compare single-query and split-query versions against the same data set.
7. Comparing lazy loading and explicit loading
Lazy loading executes a query when a navigation property is accessed. It can make application code shorter, but it hides the boundary at which database work occurs. A serializer that walks navigation properties can also cause unexpected database activity.
For this reason, list endpoints should normally prefer projection or explicit eager loading instead of making lazy loading the default behavior.
Explicit loading starts the related-data query in code:
var order = await db.Orders.FindAsync(orderId);
if (order is not null)
{
await db.Entry(order)
.Collection(o => o.Items)
.Query()
.Include(i => i.Product)
.LoadAsync();
}Explicit loading can be appropriate when the items of one particular order are needed conditionally. However, using it inside a loop can recreate the N+1 problem:
foreach (var order in orders)
{
await db.Entry(order).Collection(o => o.Items).LoadAsync();
}The number of queries now increases with the number of orders. When related data is required for many principals, use a set-based query, projection, or a carefully designed Include query.
8. Common mistakes
- Assuming lazy loading is an optimization: Avoiding unused data does not always make an operation faster. Many small queries can cost more than one controlled query.
- Including everything: Unnecessary navigation properties create wider SQL, more memory usage, and larger responses.
- Expecting Include to solve every projection: When projecting to a DTO, the required relationship is usually expressed directly through navigation access in the projection.
- Calling ToListAsync too early: Filtering or transforming after materialization moves work from the database into application memory.
- Measuring only total duration: Separate database time, command count, serialization time, and network transfer before making a decision.
- Enabling split queries everywhere: Additional round trips and consistency considerations mean that the choice should be made per query or based on a carefully tested global policy.
- Returning navigation properties directly from APIs: This can cause cycles, excessive data loading, or serializer-triggered access. Prefer dedicated DTOs.
9. Practice: compare the same endpoint
Task: Build an endpoint that returns orders created during the last 30 days and the product names contained in each order. Complete the following steps:
- Enable lazy loading, iterate through the entities, and record the total SQL command count.
- Disable lazy loading and use
Include(o => o.Items).ThenInclude(i => i.Product). - Produce the same result with a DTO projection.
- Add a second collection relationship and compare single-query behavior with
AsSplitQuery(). - Record command count, total SQL time, API duration, and response size for every approach.
| Approach | Command count | SQL time | Response size | Observation |
|---|---|---|---|---|
| Lazy loading | ... | ... | ... | N+1 risk |
| Eager loading | ... | ... | ... | Controlled Include |
| Projection | ... | ... | ... | DTO-focused |
| Split query | ... | ... | ... | Useful for multiple collections |
Do not limit the test to a tiny development database. Use at least several thousand products and a realistic distribution of orders and order items. If the database runs on another machine, also observe how network latency changes the comparison.
Conclusion
The N+1 problem usually does not come from a single incorrect LINQ expression. It comes from leaving the timing and strategy of related-data loading implicit. Lazy loading can produce concise code, but it hides query boundaries and can create serious performance problems in web applications.
When related data is known in advance, eager loading is explicit and predictable. For large collection relationships, split queries can reduce duplicated rows, but their additional round trips and consistency costs must be measured. For APIs and list screens, projection often provides the smallest and most useful result shape. The best decision comes from combining query logs, realistic data volumes, generated SQL, and repeatable measurements.
Sources
- https://learn.microsoft.com/en-us/ef/core/querying/related-data/
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/ef/core/querying/single-split-queries
- https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy
- https://learn.microsoft.com/en-us/ef/core/performance/performance-diagnosis
- https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/