Entity Framework Core Advanced

EF Core performance tips

EF Core is fast when used well and slow when used carelessly. This lesson collects the most effective performance habits: loading only what you need, avoiding extra round trips, paging, indexing and checking the SQL that EF Core generates.

EF Core performance checklist
  1. Read-only? AsNoTrackingSkips change tracking overhead
  2. Project with SelectFetch only the columns the page uses
  3. Avoid N+1Use Include or projections instead of queries in loops
  4. Page large listsOrderBy with Skip and Take
  5. Index filtered columnsHasIndex in the model, created by migrations
  6. Many collection Includes?AsSplitQuery avoids huge joined results
  7. Bulk changesExecuteUpdateAsync and ExecuteDeleteAsync
  8. Look at the SQLLog queries and read execution plans

The idea in plain words

Most EF Core slowness comes from asking the database for too much data, too many times. The fixes are usually small changes to queries rather than big rewrites. Measure first: log the SQL EF Core generates, find slow or repeated queries, then apply the tips in the checklist.

Example: a fast list page

C#
var page = await db.Products
    .AsNoTracking()
    .Where(p => p.CategoryId == categoryId)
    .OrderBy(p => p.Name)
    .Skip((pageNumber - 1) * 20).Take(20)
    .Select(p => new ProductRow(p.Id, p.Name, p.Price))
    .ToListAsync();

// Model configuration: index the filtered column
modelBuilder.Entity<Product>().HasIndex(p => p.CategoryId);

// Two collection includes: split into separate SQL queries
var customer = await db.Customers
    .Include(c => c.Orders)
    .Include(c => c.Addresses)
    .AsSplitQuery()
    .FirstAsync(c => c.Id == id);

Seeing the SQL and reusing contexts

Log the generated SQL in development. For very busy apps, DbContext pooling reuses context instances instead of creating new ones for every request.

C#
builder.Services.AddDbContextPool<ShopContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
    if (builder.Environment.IsDevelopment())
        options.LogTo(Console.WriteLine, LogLevel.Information);
});

Common mistakes

  • Loading whole entities with many columns for a list that shows two of them.
  • Calling SaveChanges inside a loop.
  • Using EnableSensitiveDataLogging in production, which writes parameter values (possibly personal data) to logs.
  • Optimizing without measuring first.

Interview question

What is the cartesian explosion problem in EF Core and how do you fix it?

When a query eagerly loads two or more collection navigations with Include, the single SQL JOIN returns the product of the rows, for example 10 orders times 10 addresses gives 100 rows per customer, with lots of duplicated data. Fix it with AsSplitQuery, which loads each collection with a separate SQL query, or by projecting only the data you need.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.