Introduction
A query returning the correct results is not necessarily an efficient query. In list screens, it is common to load an entire entity graph even though the user interface displays only a few fields. This creates unnecessary database, network, CPU and memory costs. EF Core makes these queries easy to write, but code that is easy to write does not always perform well in production.
In this lesson, we will examine unnecessary data loading through an order-list scenario. First, we will review a flawed approach that loads complete entities and related data with Include. Then we will replace it with a corrected query that uses Select-based DTO projection, AsNoTracking and pagination. Finally, we will inspect the generated SQL and explain why the corrected query transfers less data.
The central principle is simple: A screen usually does not need an entity object. It needs a specific data shape designed for that screen.
1. Model and problem scenario
Assume that an order has a customer and a collection of order items. Products also contain a large Description field that is not displayed in the order list.
public class Order
{
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public string Status { get; set; } = null!;
public int CustomerId { get; set; }
public Customer Customer { get; set; } = null!;
public ICollection<OrderItem> Items { get; set; } = new List<OrderItem>();
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; } = null!;
public string Email { get; set; } = null!;
public string Address { get; set; } = null!;
}
public class OrderItem
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public Product Product { get; set; } = null!;
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public string Description { get; set; } = null!;
public string InternalNotes { get; set; } = null!;
}The list screen displays only the order number, date, status, customer name, item count and total amount. Nevertheless, the following query loads the customer's address and email, product descriptions and internal notes, as well as every order-item entity.
var orders = await dbContext.Orders
.Include(o => o.Customer)
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.OrderByDescending(o => o.CreatedAt)
.ToListAsync();This code may work correctly, but it retrieves much more data than the list screen needs. Because the result is made up of entities, EF Core also tracks the objects by default. For a read-only screen, this tracking overhead is unnecessary.
2. Entity loading versus projection
Entity loading converts database rows into application entity instances and, in the default configuration, prepares them for change tracking. This is useful when the application will modify those objects and persist the changes with SaveChangesAsync.
Projection uses Select to transform the query into a new data shape containing only the required fields. The target can be an anonymous type, a record or a DTO. With projection, EF Core can place the selected properties in the SQL SELECT list and avoid loading columns that are not needed.
Projection is often the better choice for lists, reports, search results, dashboards and API responses. These scenarios usually read data without modifying the returned entities.
3. The first correction with DTO projection
Define a DTO for the data required by the list screen.
public sealed record OrderListItemDto(
int Id,
DateTime CreatedAt,
string Status,
string CustomerName,
int ItemCount,
decimal TotalAmount);Now project the query directly into that DTO.
var orders = await dbContext.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Select(o => new OrderListItemDto(
o.Id,
o.CreatedAt,
o.Status,
o.Customer.FullName,
o.Items.Count(),
o.Items.Sum(i => i.Quantity * i.UnitPrice)))
.ToListAsync();No Include is required here. The navigation properties are used inside the projection to identify the fields needed by the DTO. EF Core can translate Customer.FullName, Items.Count() and Items.Sum(...) into provider-supported SQL expressions. The application receives only the DTO values rather than complete customer and product entities.
AsNoTracking also communicates the intention of the query: the result is read-only and will not be modified and saved through the same context. Since the projection creates a DTO instead of returning an entity, tracking is already less relevant; however, explicitly using AsNoTracking documents the read-only behavior and protects the query if entity portions are later added.
4. Excluding large text columns
Large descriptions, HTML content, JSON documents, image data and internal notes are frequently loaded even when a list displays none of them. If a product catalog shows only the name and price, there is no reason to load the complete product entity.
public sealed record ProductListItemDto(
int Id,
string Name,
decimal Price);var products = await dbContext.Products
.AsNoTracking()
.Where(p => p.IsActive)
.OrderBy(p => p.Name)
.Select(p => new ProductListItemDto(
p.Id,
p.Name,
p.Price))
.ToListAsync();This is different from loading the complete Product entity and ignoring some properties afterward. Projection aims to move the selection to the database level. As a result, fewer columns need to cross the network and EF Core has fewer values to materialize into application objects.
5. Projection alone does not replace pagination
Projection reduces the number of columns, but it does not automatically reduce the number of rows. Selecting six fields from millions of orders can still produce an excessively large result set. List queries should therefore also use pagination.
A simple page-number implementation can use Skip and Take:
var pageNumber = 3;
var pageSize = 25;
var orders = await dbContext.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.ThenByDescending(o => o.Id)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.Select(o => new OrderListItemDto(
o.Id,
o.CreatedAt,
o.Status,
o.Customer.FullName,
o.Items.Count(),
o.Items.Sum(i => i.Quantity * i.UnitPrice)))
.ToListAsync();A deterministic ordering is important. If several orders have the same creation timestamp and no secondary ordering is specified, records can move between pages. In this example, Id provides a stable second ordering key.
Skip and Take are an understandable starting point for many applications. For very large offsets or continuously advancing feeds, keyset pagination can be more efficient because it continues from the last seen key. The important point in this lesson is that projection and result-size limits should be considered together.
6. Comparing the flawed and corrected approaches
| Concern | Flawed approach | Corrected approach |
|---|---|---|
| Result type | Complete entity graph | Purpose-specific DTO |
| Relationships | Several Include calls | Fields selected inside the projection |
| Large columns | Loaded by default | Excluded from Select |
| Tracking | May be enabled by default | AsNoTracking for read-only data |
| Row count | Entire result set | Limited with Skip and Take |
| Maintenance | Tightly coupled to the entity model | Coupled to the screen's data contract |
The corrected query may not produce exactly the same SQL shape for every provider or expression. The database provider and query form influence translation. Therefore, do not judge the result only by reading the C# code; inspect the actual SQL as well.
7. Inspecting generated SQL
ToQueryString can be used to inspect the SQL representation of an EF Core query during development.
var query = dbContext.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Select(o => new OrderListItemDto(
o.Id,
o.CreatedAt,
o.Status,
o.Customer.FullName,
o.Items.Count(),
o.Items.Sum(i => i.Quantity * i.UnitPrice)))
.Take(25);
var sql = query.ToQueryString();
Console.WriteLine(sql);Do not write sensitive data to the console or unprotected text logs in production. During development, SQL logging is useful, but parameter values may contain personal or confidential information.
When reviewing the SQL, ask the following questions:
- Are the selected columns limited to the values required by the DTO?
- Is there an unnecessary
JOINor collection load? - Are filtering, ordering and pagination executed in the database?
- Are aggregates such as
COUNTandSUMcalculated by the database, or are all rows loaded first? - Do suitable indexes exist for the filtering and ordering columns?
8. Common mistakes
Adding unnecessary Include after projection
When a DTO projection already specifies the required fields, Include is usually unnecessary. Projection makes the selected data explicit. Combining both approaches can make the query more complex and obscure its intent.
Calling ToListAsync too early
var allOrders = await dbContext.Orders.ToListAsync();
var result = allOrders
.Select(o => new OrderListItemDto(
o.Id,
o.CreatedAt,
o.Status,
o.Customer.FullName,
o.Items.Count,
o.Items.Sum(i => i.Quantity * i.UnitPrice)))
.Take(25)
.ToList();In this example, the database query executes when ToListAsync is called. The later projection and Take operations run in memory. A better order is to compose filtering, ordering, projection and pagination on the IQueryable, then call ToListAsync at the end.
Returning entities instead of DTOs
Returning entities directly from an API can expose unnecessary fields and couple the external data contract to the persistence model. If a new property is added to the entity later, the response can grow without an intentional API design decision.
Using projection where an update is required
Projection is excellent for read operations. If a record must be updated, take care not to attach a DTO and accidentally overwrite properties that were not included. Loading a tracked entity or using a carefully controlled attach-and-modify approach may be more appropriate for updates.
9. Practice exercise
Apply the following task in your existing troubleshooting laboratory:
- Create an
Orderstable containing at least 1,000 records. - Run the existing list query that uses
IncludeandThenInclude. - Record the SQL logs and execution time.
- Define an
OrderListItemDtoand rewrite the same screen using only the required fields. - Add
AsNoTracking,OrderBy,SkipandTake. - Compare the
ToQueryStringoutput and transferred result size of both queries. - Write a short explanation of why the detail screen may require a different projection.
Do not evaluate the exercise only by asking whether the second query is shorter. Compare the selected columns, returned rows, SQL plan, memory usage and readability of the data-access code.
Conclusion
Unnecessary data loading often produces no exception. The application may appear to work correctly, and the problem can remain hidden while development databases contain only a small amount of data. As production data grows, response times increase, memory usage rises and the database performs unnecessary work.
The solution is systematic: define the data shape the screen actually needs, use Select-based DTO projection, exclude large columns, prefer AsNoTracking for read-only queries and limit the result set with pagination. Then inspect the generated SQL to validate your assumptions.
During your next EF Core performance review, ask: “Is this query loading the entire entity graph, or only the data that the user will see?” Making that question part of your routine is an important step toward maintainable and measurable data-access code.