LESSON 4 OF 13

AsNoTracking, Projections, and Reducing Unnecessary Data Transfer

Learn how to use AsNoTracking and DTO projections for read-only queries, reduce change-tracker and entity-graph costs, and compare alternative EF Core queries with BenchmarkDotNet.

40 dk 69

Introduction

An ASP.NET Core API is not necessarily slow because the database itself is slow. Even when a query executes quickly, the application may read too many columns, materialize a large entity graph, keep thousands of objects in the change tracker, or send fields that the client never uses. These costs become especially visible in listing, search, and reporting endpoints.

In this lesson, we will use AsNoTracking for read-only scenarios, apply DTO projections to select only the required fields, and examine why broad Include chains should be used carefully. In the final section, we will compare alternative queries with BenchmarkDotNet.

Our examples use a product catalog. A product detail page may need many entity properties, but a product list commonly needs only an identifier, name, price, and category name. The central performance principle is that every query should return data appropriate for its actual use case.

1. Tracking and No-Tracking

EF Core tracks results by default when a query returns entity types. The change tracker stores original values and relationship information for loaded objects. When SaveChangesAsync is called, EF Core uses this information to determine what has changed.

This behavior is necessary for update workflows, but it adds overhead to data that is only displayed. With AsNoTracking, EF Core does not add the returned entities to the change tracker and does not create snapshots for change detection.

var products = await db.Products
    .Where(p => p.IsActive)
    .AsNoTracking()
    .ToListAsync();

Changes made to these product objects will not automatically be persisted by SaveChangesAsync. Therefore, the following code is incorrect:

var product = await db.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == request.Id);

product.Price = request.Price;
await db.SaveChangesAsync(); // The change is not being tracked.

If the entity will be modified, use a tracking query or explicitly attach and mark the required properties:

var product = await db.Products
    .SingleAsync(p => p.Id == request.Id);

product.Price = request.Price;
await db.SaveChangesAsync();

The goal is not to add AsNoTracking everywhere. First classify the query. Listing, search, reporting, and response-building queries are commonly read-only. Updates, deletes, and workflows that coordinate several related entities may require tracking.

Identity resolution

Tracking queries can reuse an entity with the same key when it has already been materialized in the current context. In a no-tracking query, the same entity may be materialized as separate object instances if it appears multiple times in the result. If repeated related entities are important, consider AsNoTrackingWithIdentityResolution.

var orders = await db.Orders
    .AsNoTrackingWithIdentityResolution()
    .Include(o => o.Customer)
    .ToListAsync();

This option still has a cost because EF Core performs temporary identity resolution during materialization. In many listing APIs, using DTO projections avoids materializing entity instances altogether, making the distinction less significant.

2. DTO Projections Instead of Include

Include is useful when related data must be loaded as part of an entity graph. However, loading a broad graph can read more columns, return more rows, repeat data because of joins, and materialize more objects than the screen actually needs.

The following query loads products with categories and reviews:

var products = await db.Products
    .Include(p => p.Category)
    .Include(p => p.Reviews)
    .ThenInclude(r => r.User)
    .Where(p => p.IsActive)
    .ToListAsync();

This may be excessive for a product list. Assume that the screen displays only the product name, price, category name, and average rating. A DTO projection is a better fit:

public sealed class ProductListItemDto
{
    public int Id { get; init; }
    public string Name { get; init; } = string.Empty;
    public decimal Price { get; init; }
    public string CategoryName { get; init; } = string.Empty;
    public double AverageRating { get; init; }
}

var products = await db.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .Select(p => new ProductListItemDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price,
        CategoryName = p.Category.Name,
        AverageRating = p.Reviews
            .Where(r => r.IsApproved)
            .Select(r => (double?)r.Rating)
            .Average() ?? 0
    })
    .ToListAsync();

EF Core can translate the projection into SQL based on the fields used by the DTO. Unused values such as a long description, internal notes, image bytes, or JSON metadata do not need to cross the database boundary. The category and review entities also do not need to be fully materialized.

Should Include be combined with projection?

When a projection accesses related values through navigations, such as p.Category.Name, EF Core can include the required value in the generated query. In this case, adding Include(p => p.Category) is usually unnecessary. Include is primarily intended for scenarios where entities are returned and related entities are needed as part of the result.

Avoid returning the entity itself inside a projection:

var result = await db.Products
    .Select(p => new
    {
        Product = p,
        CategoryName = p.Category.Name
    })
    .ToListAsync();

Because the result contains a Product entity, tracking behavior may still apply. For a read-only response, select scalar values or DTO properties only:

var result = await db.Products
    .AsNoTracking()
    .Select(p => new
    {
        p.Id,
        p.Name,
        CategoryName = p.Category.Name
    })
    .ToListAsync();

3. Reducing Unnecessary Data Transfer

Query performance is not limited to database execution time. Data transferred from the database, materialization work, application memory, and HTTP response size all contribute to the total cost.

Imagine that Product contains a long description, a JSON metadata field, and image bytes. Returning entities directly from a list endpoint can send all of these unused values to the client:

[HttpGet]
public async Task<IActionResult> GetProducts()
{
    var products = await db.Products
        .AsNoTracking()
        .Where(p => p.IsActive)
        .ToListAsync();

    return Ok(products);
}

A more controlled endpoint can project the response shape explicitly:

[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductListItemDto>>> GetProducts()
{
    var products = await db.Products
        .AsNoTracking()
        .Where(p => p.IsActive)
        .OrderBy(p => p.Name)
        .Select(p => new ProductListItemDto
        {
            Id = p.Id,
            Name = p.Name,
            Price = p.Price,
            CategoryName = p.Category.Name,
            AverageRating = p.Reviews
                .Where(r => r.IsApproved)
                .Select(r => (double?)r.Rating)
                .Average() ?? 0
        })
        .ToListAsync();

    return Ok(products);
}

Pagination is also important for list endpoints. Limit the result set and keep ordering deterministic:

var pageSize = Math.Clamp(request.PageSize, 1, 100);
var page = Math.Max(request.Page, 1);

var items = await db.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .OrderBy(p => p.Id)
    .Select(p => new ProductListItemDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price,
        CategoryName = p.Category.Name,
        AverageRating = p.Reviews
            .Where(r => r.IsApproved)
            .Select(r => (double?)r.Rating)
            .Average() ?? 0
    })
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

Projection without pagination only makes each row smaller. If the table contains millions of matching rows, the query can still be expensive.

4. Comparing Query Approaches

Do not select an optimization only because the code appears shorter. Inspect the generated SQL, selected columns, number of returned rows, execution time, allocated memory, and behavior with realistic data volumes. The SQL logging and query-analysis techniques from the previous lesson remain useful here.

BenchmarkDotNet can collect more consistent microbenchmark results. The following example compares a broad entity graph with a no-tracking projection:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.EntityFrameworkCore;

[MemoryDiagnoser]
public class ProductQueryBenchmark
{
    private CatalogDbContext _db = null!;

    [GlobalSetup]
    public void Setup()
    {
        _db = CreateContext();
    }

    [Benchmark(Baseline = true)]
    public async Task<int> IncludeEntityGraph()
    {
        var products = await _db.Products
            .Include(p => p.Category)
            .Include(p => p.Reviews)
            .Where(p => p.IsActive)
            .ToListAsync();

        return products.Count;
    }

    [Benchmark]
    public async Task<int> NoTrackingProjection()
    {
        var products = 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,
                AverageRating = p.Reviews
                    .Where(r => r.IsApproved)
                    .Select(r => (double?)r.Rating)
                    .Average() ?? 0
            })
            .ToListAsync();

        return products.Count;
    }

    private static CatalogDbContext CreateContext()
    {
        throw new NotImplementedException();
    }
}

public static class Program
{
    public static void Main() =>
        BenchmarkRunner.Run<ProductQueryBenchmark>();
}

In a real benchmark, CreateContext should return a context factory connected to a prepared database with stable test data. Every benchmark should use the same row counts, indexes, schema, and comparable connection conditions. First-query warm-up and database caching can otherwise distort the results.

MemoryDiagnoser helps compare allocated memory and garbage-collection behavior. It does not represent the complete latency of an HTTP endpoint. JSON serialization, networking, authentication, connection-pool waits, and client behavior must be measured separately. Use BenchmarkDotNet to isolate query and materialization costs, and use load testing and application telemetry for endpoint-level measurements.

5. Common Mistakes

  • Adding AsNoTracking everywhere: Applying it to entities that must be updated changes the expected SaveChanges behavior.
  • Returning entities from a DTO projection: Including the entity itself can reintroduce tracking and unnecessary materialization.
  • Using a broad Include chain in a list endpoint: A graph that is appropriate for a detail page may be unnecessarily expensive for a list.
  • Calling ToListAsync too early: Loading all rows into memory before applying Where, Select, or Take prevents the database from doing the work efficiently.
  • Benchmarking in Debug mode: Use a Release build and avoid unrelated heavy work during measurements.
  • Looking only at average duration: Also inspect allocated memory, correctness, p95 latency, response size, and the database query plan.

6. Practice Exercise

Refactor an existing product-list endpoint by following these steps:

  1. Identify which columns and related entities the current entity query loads.
  2. Change the query to use AsNoTracking because the endpoint is read-only.
  3. Create a response DTO similar to ProductListItemDto.
  4. Remove the broad Include chain and project the category name, price, and required summary fields with Select.
  5. Limit the page size and add deterministic ordering.
  6. Compare the generated SQL before and after the change and record the selected columns.
  7. Run at least three BenchmarkDotNet measurements and record both duration and allocated memory.

When interpreting the results, do not ask only whether the new query is faster. Also verify that the returned data is equivalent, the response is smaller, memory consumption changed as expected, and the query behaves well at realistic data volumes.

Conclusion

AsNoTracking is an important tool for reducing change-tracker overhead in read-only queries, but using it blindly can break update workflows. DTO projections select only the required columns, avoid materializing complete related graphs, and help keep API responses small.

The strongest results usually come from combining purpose-appropriate tracking, narrow projections, bounded result sets, controlled relationship loading, and repeatable measurements. Before shipping an optimization, evaluate SQL, memory usage, response size, and real request latency together. In the next lessons, we will combine these query improvements with pagination and caching strategies.

Sources