Improving EF Core Query Performance with Projections, Pagination, and Index-Aware Design

Improving EF Core Query Performance with Projections, Pagination, and Index-Aware Design

Entity Framework Core makes database access approachable through LINQ, but readable query code is not automatically efficient query code. A query that appears fast against a small development database may later retrieve too many columns, materialize unnecessary rows, or prevent the database from using an appropriate index.

This article presents a repeatable approach for EF Core read paths: select only the fields the caller needs, bound the result set, align filters and ordering with indexes, choose tracking deliberately, and inspect the SQL and execution plan before declaring a query optimized.

Define the read shape first

An API requirement such as “get customers” is not precise enough to design a query. Which customers should be included? Which fields are displayed? How many rows are allowed? What ordering is required? Is the result intended for editing or only for presentation?

If a list needs only an identifier, name, and latest order date, project directly into a response model instead of loading the complete entity:

var customers = await db.Customers
    .Where(c => c.IsActive)
    .OrderBy(c => c.Name)
    .Select(c => new CustomerListItem
    {
        Id = c.Id,
        Name = c.Name,
        LastOrderDate = c.Orders
            .OrderByDescending(o => o.CreatedAt)
            .Select(o => (DateTime?)o.CreatedAt)
            .FirstOrDefault()
    })
    .Take(50)
    .AsNoTracking()
    .ToListAsync(cancellationToken);

This technique, commonly called projection, lets the provider request only the columns needed by the result. It can reduce transferred data, object materialization, and memory usage. It also keeps an HTTP response model from being coupled directly to the persistence entity.

Design indexes around real queries

An index is not a universal performance switch. It helps when its columns match the filtering, ordering, and access patterns of a real workload. Consider this query:

var orders = await db.Orders
    .Where(o => o.TenantId == tenantId && o.Status == OrderStatus.Open)
    .OrderByDescending(o => o.CreatedAt)
    .Take(50)
    .AsNoTracking()
    .ToListAsync(cancellationToken);

Depending on the database provider and workload, a composite index involving TenantId, Status, and CreatedAt may be worth evaluating:

modelBuilder.Entity<Order>()
    .HasIndex(o => new { o.TenantId, o.Status, o.CreatedAt });

The column order must be intentional. A composite index can support some predicates and orderings while being much less useful for others. Indexes also have a write cost because they must be maintained when rows are inserted or changed. Adding an index to every frequently queried column can therefore create a different bottleneck.

Validate index choices with the database's execution plan. During development, ToQueryString() can help you inspect the SQL generated by EF Core. It is not a substitute for measuring against realistic data volumes, representative parameters, and the actual database engine used in production.

Always bound the result set

A query ending with ToListAsync() can load every matching row into memory. That may be acceptable for a small, fixed lookup table, but it is risky for user-generated or operational data that grows over time.

At minimum, impose an explicit limit:

var page = await db.Products
    .Where(p => p.IsPublished)
    .OrderBy(p => p.Id)
    .Select(p => new ProductItem(p.Id, p.Name, p.Price))
    .Take(100)
    .AsNoTracking()
    .ToListAsync(cancellationToken);

For user-facing pagination, two common strategies are available:

  • Offset pagination: Uses Skip and Take. It is convenient when users need numbered pages, but deep offsets can require the database to process many rows before returning the requested page.
  • Keyset pagination: Continues from the last value seen by the client. It can provide more stable navigation for large, changing datasets, but moving directly to an arbitrary page requires a separate design.

Keyset pagination needs deterministic ordering. If several rows can share the same timestamp, add a unique tie-breaker:

var query = db.Products
    .Where(p => p.IsPublished)
    .OrderByDescending(p => p.CreatedAt)
    .ThenByDescending(p => p.Id);

The next-page predicate must compare both CreatedAt and Id. Otherwise, rows with equal timestamps can be duplicated or skipped between requests.

Choose tracking according to the use case

EF Core can track entity instances returned by a query. Tracking is useful when the same context will later persist changes to those entities. For read-only lists and reports, tracking may add work that the request does not need.

Use AsNoTracking() when the query is explicitly read-only:

var reportRows = await db.Invoices
    .Where(i => i.IssuedAt >= fromDate && i.IssuedAt < toDate)
    .Select(i => new InvoiceRow
    {
        Id = i.Id,
        Number = i.Number,
        Total = i.Total
    })
    .AsNoTracking()
    .ToListAsync(cancellationToken);

Projection into a DTO or anonymous type is already a strong indication that the result is not an editable entity graph. Keeping AsNoTracking in the query can still make the intent visible to maintainers.

Do not apply no-tracking mechanically everywhere. If an entity is loaded, modified, and saved within the same context, tracking is part of the expected workflow. A performance convention that ignores the write path can create update bugs or force unnecessary reattachment code.

Control related data and avoid N+1 queries

The N+1 problem occurs when an initial query loads a list and then an additional query is executed for each item. Lazy loading can make this especially easy to trigger when a navigation property is accessed inside a loop.

For a summary screen, express the required related values in one projection:

var summaries = await db.Blogs
    .Select(b => new BlogSummary
    {
        Id = b.Id,
        Url = b.Url,
        PostCount = b.Posts.Count(),
        LatestTitle = b.Posts
            .OrderByDescending(p => p.PublishedAt)
            .Select(p => p.Title)
            .FirstOrDefault()
    })
    .AsNoTracking()
    .ToListAsync(cancellationToken);

Loading multiple collection navigations in a single query can also produce duplicated joined rows in some shapes. Before using a large Include graph, ask whether the caller really needs entities and relationships, or only a compact read model. For lists and reports, projection often gives you clearer control over the result.

Use asynchronous APIs with realistic expectations

Methods such as ToListAsync and FirstOrDefaultAsync avoid synchronously blocking the application thread while database I/O is in progress. They do not, however, make an inefficient query intrinsically faster. Missing indexes, large result sets, and expensive execution plans still need to be addressed.

Pass the request's cancellation token through the query so abandoned HTTP requests do not unnecessarily continue all application work:

await db.Products
    .Where(p => p.IsPublished)
    .Select(p => new ProductItem(p.Id, p.Name, p.Price))
    .ToListAsync(cancellationToken);

A practical review checklist

  • Does the query select only the columns required by the caller?
  • Is there an explicit limit or pagination strategy?
  • Is ordering deterministic, including a unique tie-breaker where needed?
  • Do filters and ordering align with an index supported by the database engine?
  • Is change tracking actually required for this read path?
  • Could navigation-property access inside a loop cause N+1 queries?
  • Have the generated SQL and execution plan been reviewed using realistic data?
  • Is the request cancellation token passed to the asynchronous EF Core operation?

Conclusion

EF Core query performance comes from aligning the application's read shape with the database's execution strategy. Use projections to keep responses and SQL small, bound every potentially growing result set, design indexes from measured query patterns, and make tracking an intentional choice. Finally, inspect the generated SQL and execution plan rather than treating an optimization as proven merely because the code looks simpler.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published