Fast Read Queries in EF Core 10: Projections, No-Tracking and Paging

Most slow EF Core pages come from four habits. Fix them with projections, AsNoTracking, database paging and split queries, and check the SQL.

R M Shahidul Islam Shahed · 4 min read

Most slow EF Core pages aren't slow because EF Core is slow. They're slow because of a few habits: loading whole entities to show three columns, tracking objects nobody will save, paging in memory, and joining collections into a huge result set. This post fixes each one on EF Core 10, and shows how to check the SQL you actually send.

Start by looking at the SQL

You can't tune what you can't see. In development, log the SQL EF Core generates:

json
{
  "Logging": {
    "LogLevel": {
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

For a single query, ToQueryString() shows the SQL without running it:

csharp
var sql = db.Posts.Where(p => p.Status == PostStatus.Published).ToQueryString();

Paste it into SQL Server Management Studio, turn on the actual execution plan, and you'll see which index (if any) is used.

Habit 1: loading whole entities for a list

A post entity carries the Markdown body, the rendered HTML and more. A list page needs a title, a date and a slug.

csharp
// Loads every column, including two large nvarchar(max) fields, for every row.
var posts = await db.Posts.Where(p => p.Status == PostStatus.Published).ToListAsync(ct);

Project into exactly what the page shows:

csharp
public sealed record PostCardVm(string Slug, string Title, string Excerpt, string Topic, DateTime? PublishedAt);

var cards = await db.Posts
    .Where(p => p.Status == PostStatus.Published)
    .OrderByDescending(p => p.PublishAtUtc)
    .Select(p => new PostCardVm(p.Slug, p.Title, p.Excerpt, p.Category!.Name, p.PublishAtUtc))
    .ToListAsync(ct);

The SELECT now names five columns, and the join to Categories happens in SQL. No Include is needed: navigation properties used inside Select are translated to joins.

Keep the projection in one reusable expression so every list uses the same shape:

csharp
public static readonly Expression<Func<Post, PostCardVm>> ToCard =
    p => new PostCardVm(p.Slug, p.Title, p.Excerpt, p.Category!.Name, p.PublishAtUtc);

var cards = await query.Select(ToCard).ToListAsync(ct);

Habit 2: tracking what you'll never save

When EF Core tracks an entity it keeps a snapshot to detect changes later. For read-only pages that work is wasted.

csharp
var post = await db.Posts.AsNoTracking().FirstOrDefaultAsync(p => p.Slug == slug, ct);

Projections into records aren't tracked anyway, so AsNoTracking matters most when you load entities. If a whole context is read-only (a reporting service, say), set it once:

csharp
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

Habit 3: paging in memory

csharp
// Reads every row, then throws most of them away.
var page = (await db.Posts.ToListAsync(ct)).Skip(40).Take(20);

Page in the database, with a stable order:

csharp
var page = await db.Posts
    .Where(p => p.Status == PostStatus.Published)
    .OrderByDescending(p => p.PublishAtUtc).ThenByDescending(p => p.Id)
    .Skip((pageNumber - 1) * size)
    .Take(size)
    .Select(ToCard)
    .ToListAsync(ct);

Always add a tie-breaker such as ThenByDescending(p => p.Id). Without it, rows with the same date can swap between pages and appear twice or not at all.

For deep pages on large tables, OFFSET gets slower as the page number grows. Keyset paging ("posts older than the last one I saw") stays fast:

csharp
var next = await db.Posts
    .Where(p => p.PublishAtUtc < lastSeenDate || (p.PublishAtUtc == lastSeenDate && p.Id < lastSeenId))
    .OrderByDescending(p => p.PublishAtUtc).ThenByDescending(p => p.Id)
    .Take(size)
    .Select(ToCard)
    .ToListAsync(ct);

"Load more" buttons are a natural fit for keyset paging.

Habit 4: one giant join for many collections

Including two collections in one query multiplies rows: 10 tags times 50 comments is 500 rows per post.

csharp
var post = await db.Posts
    .Include(p => p.PostTags).ThenInclude(pt => pt.Tag)
    .Include(p => p.Comments)
    .AsSplitQuery()
    .FirstAsync(p => p.Id == id, ct);

AsSplitQuery() sends one query per collection instead of one exploding join. It costs extra round trips, so use it when you include more than one collection, not by default.

Indexes that match your queries

EF Core can't make up for a missing index. Declare indexes next to the entity configuration so they ship with migrations:

csharp
b.HasIndex(p => new { p.Status, p.PublishAtUtc })
    .IsDescending(false, true)
    .IncludeProperties(p => new { p.Title, p.Excerpt, p.Slug })
    .HasFilter("[IsDeleted] = 0");

An index on (Status, PublishAtUtc DESC) that includes the listed columns lets SQL Server answer the list query from the index alone.

Count without loading

csharp
var total = await query.CountAsync(ct);                 // SELECT COUNT(*)
var any = await query.AnyAsync(p => p.IsFeatured, ct);  // SELECT CASE WHEN EXISTS(...)

Never call ToListAsync() only to read .Count.

A checklist for every list page

  • Project with Select into a view model.
  • AsNoTracking() when you load entities you won't save.
  • Page in SQL with a stable order and a tie-breaker.
  • AsSplitQuery() when including more than one collection.
  • An index that matches the WHERE and ORDER BY.
  • Read the SQL once before you ship.

Wrapping up

EF Core 10 produces good SQL when you ask for what you need. Project, skip tracking for reads, page in the database and give SQL Server the right index. Those four changes fix most slow pages before you need anything clever.

Keep reading

All articles →
EF Core & Databases

12 EF Core Performance Tips That Actually Matter

AsNoTracking, compiled queries, split queries and bulk updates — measured on a real ERP database, not a toy sample.

1 min read
EF Core & Databases

Optimistic Concurrency in EF Core with rowversion

Two people edit the same record and the second save silently wins. Stop lost updates with a rowversion column and a clear message.

4 min read
Performance & Optimisation

Measure Before You Optimise: BenchmarkDotNet for .NET Developers

Stopwatch timings lie. Set up BenchmarkDotNet, read its results, measure allocations and avoid the mistakes that make benchmarks meaningless.

4 min read