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:
{
"Logging": {
"LogLevel": {
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
}
}For a single query, ToQueryString() shows the SQL without running it:
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.
// 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:
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:
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.
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:
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);Habit 3: paging in memory
// 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:
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:
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.
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:
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
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
Selectinto 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
WHEREandORDER 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.