loading experience

Entity Framework Core

EF Core: ten tips for faster queries

Projections, AsNoTracking, split queries and bulk updates: the habits that make a difference.

EF Core: ten tips for faster queries

Entity Framework Core is productive, but a few habits can turn a fast page into a slow one. Here are the tips we apply in every project.

The same information, with far less work for the database.
The same information, with far less work for the database.

1. Read only what you need

var list = await db.Products
    .Where(p => p.IsActive)
    .Select(p => new ProductRow(p.Id, p.Name, p.Price))
    .ToListAsync();

2. AsNoTracking for reads

If you do not need to modify the entities, AsNoTracking() avoids the cost of the change tracker.

3. Watch out for the N+1 problem

Loading a list and then accessing a relationship inside a loop generates one query per row. Use Include or, better, a projection that brings the related data along.

4. Split queries for multiple collections

Including several collections in the same query multiplies the rows returned. AsSplitQuery() loads them with separate queries.

5. Always paginate in the database

var page = await db.Orders
    .OrderByDescending(o => o.Date)
    .Skip((number - 1) * size)
    .Take(size)
    .ToListAsync();

6. Bulk updates

await db.Sessions
    .Where(s => s.ExpiresAt < DateTime.UtcNow)
    .ExecuteDeleteAsync();

7-10. The other habits

  • Indexes on columns used in filters and sorting: no ORM makes up for a missing index.
  • Compiled queries for the most frequent queries.
  • DbContext pooling with AddDbContextPool in high-traffic applications.
  • Look at the generated SQL: ToQueryString() and command logging show what really reaches the database.
Comments (0)

No comments yet.

Leave a comment