Entity Framework Core makes it easy to retrieve related data using navigation properties, Include(), and ThenInclude(). These features reduce the amount of database access code developers need to write.
However, loading related entities efficiently requires more attention as an application grows.
Consider an application that retrieves customer orders along with their products, payments, and delivery information. A query that loads all these relationships may generate a large SQL statement. In another situation, accessing navigation properties inside a loop may execute additional database queries for every record.
Both situations can affect production performance.
Developers may notice repeated SQL statements, duplicated entity objects, unnecessary database round trips, or large result sets even when the application appears to execute only one LINQ query.
The solution is not simply to add more Include() statements or enable no-tracking queries everywhere. Developers need to understand how EF Core loads related entities, how identity resolution works, and when eager, explicit, or lazy loading is appropriate.
This article explains practical ways to prevent unnecessary related-data loading and improve EF Core query performance.
Understand Why EF Core Loads Related Data More Than Once
Consider a simple database structure:
- Customer has many Orders.
- Order has many OrderItems.
- OrderItem references a Product.
- Order has a Payment.
A typical entity relationship might look like this:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ICollection<Order> Orders { get; set; }
= new List<Order>();
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; } = null!;
public ICollection<OrderItem> OrderItems { get; set; }
= new List<OrderItem>();
public Payment? Payment { get; set; }
}
public class OrderItem
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; } = null!;
}
Now suppose an API retrieves orders and their related products.
var orders = await _context.Orders
.Include(o => o.OrderItems)
.ThenInclude(i => i.Product)
.ToListAsync();
This is eager loading. EF Core retrieves the requested relationships as part of the query operation.
However, depending on the query shape and related collections, the generated SQL may contain repeated parent data across multiple result rows.
For example, if one order has five items, the order's columns may appear in five joined rows.
The database is not necessarily retrieving five different orders. It is returning rows representing the relationship between the order and its items.
Understanding this distinction is important because repeated SQL rows, repeated entity instances, and repeated database queries are different problems. Each requires a different solution.
Avoid the N+1 Query Problem
One of the most common causes of unnecessary related-data loading is lazy loading.
Lazy loading retrieves related data automatically when a navigation property is accessed.
This can make application code look simple, but it can introduce additional database queries that developers do not immediately notice.
Consider the following example:
var orders = await _context.Orders
.ToListAsync();
foreach (var order in orders)
{
Console.WriteLine(order.Customer.Name);
}
If lazy loading is enabled and the customer navigation is not already loaded, accessing order.Customer can trigger another database query.
If the application retrieves 100 orders, it may execute:
- One query to retrieve orders.
- Additional queries to retrieve customers.
The exact number of additional queries depends on whether related entities are already loaded and whether identity resolution or relationship fix-up can reuse existing instances.
This behavior is commonly called the N+1 query problem.
A better approach is to explicitly load the relationship when it is required:
var orders = await _context.Orders
.Include(o => o.Customer)
.ToListAsync();
foreach (var order in orders)
{
Console.WriteLine(order.Customer.Name);
}
Now the application clearly requests the customer relationship as part of the query.
For read-only API responses, projection is often even better because it retrieves only the required fields.
var orders = await _context.Orders
.Select(o => new OrderSummaryDto
{
OrderId = o.Id,
CustomerName = o.Customer.Name,
OrderDate = o.OrderDate
})
.ToListAsync();
Projection allows EF Core to generate SQL that selects the required information without materializing complete entity graphs.
For production applications, eager loading and projection are generally easier to reason about than relying on automatic lazy loading.
Use Include and ThenInclude Carefully
The Include() and ThenInclude() methods are useful when an application genuinely needs related entities.
However, including every available relationship can create unnecessarily large queries.
Consider:
var orders = await _context.Orders
.Include(o => o.Customer)
.Include(o => o.OrderItems)
.ThenInclude(i => i.Product)
.Include(o => o.Payment)
.Include(o => o.Delivery)
.ToListAsync();
This query retrieves several relationships.
If the application needs all this information for a detailed order screen, eager loading may be appropriate.
However, if the endpoint only displays order ID, customer name, and total amount, loading every related entity wastes resources.
Use a focused projection instead:
var orders = await _context.Orders
.Select(o => new OrderDetailsDto
{
OrderId = o.Id,
CustomerName = o.Customer.Name,
TotalAmount = o.TotalAmount,
PaymentStatus = o.Payment != null
? o.Payment.Status
: "Pending"
})
.ToListAsync();
This approach avoids retrieving entire collections that the response does not need.
A useful rule is to load relationships based on the requirements of the current operation rather than the complete entity model.
Understand Cartesian Explosion in Multiple Collection Includes
Another performance problem appears when a query includes multiple collection relationships.
Consider:
var orders = await _context.Orders
.Include(o => o.OrderItems)
.Include(o => o.Payments)
.ToListAsync();
Suppose one order has:
- Five order items.
- Three payment records.
When both collections are joined in a single SQL query, the result can contain up to 15 combinations for that order.
This is called cartesian explosion.
The same order information is repeated across the joined rows, and the amount of data transferred can grow significantly as more collection relationships are included.
For example:
| Order |
Order items |
Payments |
Joined rows |
| Order A |
5 |
3 |
15 |
| Order B |
4 |
2 |
8 |
| Order C |
6 |
4 |
24 |
The database may return many rows even though the application only has three orders.
One solution is to use split queries.
var orders = await _context.Orders
.Include(o => o.OrderItems)
.Include(o => o.Payments)
.AsSplitQuery()
.ToListAsync();
With split queries, EF Core executes separate SQL queries for the included collection relationships rather than combining everything into one large join.
This can reduce duplicated data and improve performance for queries that load multiple collections.
However, split queries have trade-offs:
- They execute multiple database commands.
- Each command can introduce an additional network round trip.
- More memory may be required to buffer results.
- Data can change between queries unless an appropriate transaction isolation strategy is used.
Therefore, AsSplitQuery() should be selected based on actual query performance rather than applied everywhere.
Use Identity Resolution to Avoid Duplicate Entity Instances
Repeated entity instances are another issue developers may encounter when loading related data.
Imagine retrieving 100 orders that belong to the same customer.
Without identity resolution, EF Core may materialize multiple Customer objects representing the same database record.
This can increase memory usage and create unnecessary object duplication.
EF Core performs identity resolution automatically for tracking queries.
For example:
var orders = await _context.Orders
.Include(o => o.Customer)
.ToListAsync();
When the same customer is encountered multiple times, EF Core can reuse the existing tracked Customer instance rather than creating another instance for the same key.
This behavior is managed by the change tracker.
However, tracking introduces additional overhead because EF Core maintains entity state and snapshots for change detection.
For read-only queries, developers commonly use AsNoTracking():
var orders = await _context.Orders
.AsNoTracking()
.Include(o => o.Customer)
.ToListAsync();
This reduces change-tracking overhead, but there is an important difference: ordinary no-tracking queries do not perform identity resolution.
If the same customer appears in multiple results, EF Core may create multiple Customer instances.
When an application needs read-only results without normal change tracking but still wants to avoid duplicate entity instances, use AsNoTrackingWithIdentityResolution().
var orders = await _context.Orders
.AsNoTrackingWithIdentityResolution()
.Include(o => o.Customer)
.ToListAsync();
This performs identity resolution using a temporary change tracker for the query results. The entities are not tracked by the context in the normal way.
The choice depends on the workload:
| Query type |
Change tracking |
Identity resolution |
| Default tracking query |
Yes |
Yes |
| AsNoTracking() |
No |
No |
| AsNoTrackingWithIdentityResolution() |
No normal context tracking |
Yes |
Do not assume that no-tracking is always faster. If the result contains many repeated references to the same entities, identity resolution may reduce memory consumption and object duplication.
Measure the behavior with representative data.
Load Related Data Explicitly When It Is Actually Needed
Sometimes an application does not need every relationship immediately.
For example, an order management API might first retrieve basic order information. Only when a user opens the payment section does the application need payment details.
In this situation, explicit loading can be useful.
var order = await _context.Orders
.FirstOrDefaultAsync(o => o.Id == orderId);
if (order != null)
{
await _context.Entry(order)
.Reference(o => o.Payment)
.LoadAsync();
}
For collection relationships:
await _context.Entry(order)
.Collection(o => o.OrderItems)
.LoadAsync();
Explicit loading gives developers control over when additional database commands execute.
It is particularly useful when related information is needed conditionally.
However, do not load a collection separately for every entity in a large loop. That can recreate the N+1 problem.
If many orders need their items, consider eager loading, a projection, or a separate batch query.
Use Filtered Include for Large Collections
Sometimes an application needs only a subset of a related collection.
For example, an order details page may need only the most recent five order events.
Loading the entire collection can be unnecessary.
EF Core supports filtered Include for collection navigation properties.
var orders = await _context.Orders
.Include(o => o.OrderEvents
.Where(e => e.CreatedAt >= DateTime.UtcNow.AddDays(-30))
.OrderByDescending(e => e.CreatedAt)
.Take(5))
.ToListAsync();
This requests only a limited set of related events.
Filtered Include is useful for reducing the amount of related data retrieved, but developers should understand how it interacts with tracking.
For tracking queries, navigation fix-up may populate the navigation property with previously tracked entities that do not match the filter. The navigation can also be considered loaded even though some related records were intentionally excluded.
For predictable read-only results, a fresh context or a no-tracking query may be more appropriate.
If the application needs a specific subset of data for an API response, projection into a DTO is often the clearest option.
Use Projection Instead of Loading Complete Entity Graphs
Projection is one of the most effective ways to reduce unnecessary data loading.
Consider an endpoint that returns order information for a dashboard.
A common implementation might be:
var orders = await _context.Orders
.Include(o => o.Customer)
.Include(o => o.OrderItems)
.ThenInclude(i => i.Product)
.ToListAsync();
The application then converts the entities into response objects.
This approach loads complete entities even when the API only needs a few fields.
Instead, project directly into the required response model:
var orders = await _context.Orders
.Select(o => new OrderDashboardDto
{
OrderId = o.Id,
CustomerName = o.Customer.Name,
ItemCount = o.OrderItems.Count,
TotalAmount = o.TotalAmount,
LatestOrderDate = o.OrderDate
})
.ToListAsync();
EF Core translates the projection into SQL and retrieves the required values.
This can reduce:
- Database result size.
- Network traffic.
- Entity materialization.
- Change-tracking work.
- Application memory usage.
Projection is especially useful for dashboards, reporting APIs, search results, and list endpoints.
Avoid Reusing the Same DbContext Across Unrelated Operations
The DbContext maintains tracked entities and their relationships.
When a query retrieves entities, EF Core can use the change tracker to perform identity resolution and relationship fix-up.
This is useful within a single unit of work.
However, keeping one DbContext alive across unrelated requests or operations can cause unexpected behavior.
For example, an application may load a customer, update the customer through another process, and then query the same customer using the existing context.
The database query still executes, but EF Core can return the already tracked instance rather than replacing it with a newly materialized object.
This means the application may not see the latest database values.
Long-lived contexts also accumulate tracked entities and increase memory usage.
In ASP.NET Core applications, register the context with a scoped lifetime:
builder.Services.AddDbContext<ApplicationDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
This normally provides one context per request when resolved through the standard dependency injection scope.
For background processing, use an appropriate context lifetime or IDbContextFactory<TContext> when separate units of work are needed.
Avoid sharing a DbContext between concurrent operations. DbContext is not thread-safe.
Monitor Related-Data Loading in Production
Developers should not rely only on code inspection to identify repeated database access.
Enable appropriate EF Core command logging and inspect generated SQL.
For example:
builder.Logging.AddFilter(
"Microsoft.EntityFrameworkCore.Database.Command",
LogLevel.Information);
Look for patterns such as:
- Repeated SELECT statements for the same relationship.
- One query followed by many similar queries.
- Large JOIN statements.
- Unexpectedly large result sets.
- Queries executed inside loops.
- Repeated loading of the same collection.
Use query tags to identify the source of important database operations:
var orders = await _context.Orders
.TagWith("OrderRepository.GetOrderDetails")
.Include(o => o.OrderItems)
.ToListAsync();
Also monitor database command duration, API response time, and the number of database commands per request.
In production, avoid enabling sensitive data logging globally. It can expose confidential values in logs.
Use structured logging, targeted diagnostics, and appropriate log retention.
Common Mistakes to Avoid
| Mistake |
Better approach |
| Enabling lazy loading everywhere |
Prefer explicit eager or deliberate loading |
| Adding multiple collection Includes without measuring |
Check for cartesian explosion |
| Using AsNoTracking() without considering duplicate references |
Evaluate identity resolution requirements |
| Loading every related entity for a list endpoint |
Use projection into DTOs |
| Loading collections inside loops |
Use eager loading or batch queries |
| Keeping DbContext alive for a long time |
Use a context per unit of work |
| Applying AsSplitQuery() to every query |
Compare single and split query performance |
| Assuming filtered Include always returns only filtered entities |
Understand navigation fix-up in tracking queries |
Summary
Loading related data efficiently in EF Core requires understanding how navigation properties, eager loading, lazy loading, explicit loading, and identity resolution work together.
Repeated related-data loading can come from N+1 queries, large collection joins, duplicate entity materialization, or an unnecessarily broad entity graph.
Developers can reduce these problems by using focused Include() statements, filtered includes, projections, split queries where appropriate, and identity resolution for read-only queries that contain repeated references.
It is equally important to use short-lived DbContext instances and monitor actual SQL execution in production.
The best query is not necessarily the one with the fewest LINQ statements or the fewest SQL commands. It is the one that retrieves the required data with an appropriate balance of database round trips, transferred rows, memory usage, and application processing.
Join the conversation! Your thoughts help the community grow.