Volume 3 · Chapter 8 — Entity Framework Core and Data Access Engineering

Performance Optimization

Goutham Mayaluri 7 min read .NETC#Performance

8.1 Introduction

Data access performance determines whether an application scales - code that works with thousands of records can collapse at millions. EF Core’s convenience can hide expensive queries, so performance work means understanding how queries, tracking, connections, and generated SQL behave at runtime, and measuring rather than guessing. This chapter consolidates the EF-specific optimizations; Volumes 7 and 10 cover the broader performance discipline.

8.2 The High-Value EF Core Optimizations

A handful of techniques address most EF Core performance problems: project to select only needed columns, disable tracking for reads, eliminate N+1 queries, paginate large result sets, and ensure the database has the right indexes. These were introduced in earlier chapters; here they form a checklist.

Problem Fix
Loading full entities for a few fields Project with Select into a DTO
Tracking read-only data AsNoTracking
N+1 queries Include (eager) or a single projected query
Unbounded result sets Pagination (keyset for large tables)
Scans on large tables Add appropriate indexes

8.3 Bulk Operations and Batching

Processing thousands of rows one entity at a time creates thousands of round trips. EF Core 7+ providesExecuteUpdateandExecuteDeletefor set-based, database-side bulk operations that run in a single statement without loading entities - far faster for mass updates and deletes.


// Set-based update in the database - no entities loaded, one statement.
await db.Orders
    .Where(o => o.Status == OrderStatus.Pending && o.CreatedAt < cutoff)
    .ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, OrderStatus.Expired), ct);

8.4 Connection Pooling and Context Pooling

Opening database connections is expensive, so ADO.NET pools and reuses them automatically - you just keep connections (and DbContexts) short-lived. For high-throughput apps,AddDbContextPoolpools theDbContextinstances themselves, reducing the per-request cost of creating and configuring contexts.

8.5 Measure First and Scale Out

Performance work is measurement-driven: inspect the generated SQL, read execution plans, and use profiling before optimizing. For very large workloads, go beyond a single query - stream large reads, run heavy work as background/batch jobs, use read replicas, and adopt read-optimized models (CQRS) so reporting doesn’t contend with transactional writes.

Senior Interview Question

Walk through how you'd optimize a slow EF Core query.

I optimize by measurement, working from the actual generated SQL rather than guessing, and applying the EF- specific fixes in order of impact. First, I capture the generated SQL (EF Core query logging) so I can see exactly what runs - this immediately reveals the common culprits: SELECT * of full entities when few columns are needed, N+1 patterns (many small queries), cartesian explosions from multiple Includes, or a query pulling far more rows than necessary. Second, I take the slow SQL to the database and examine its execution plan and check indexes, because the most common cause of a slow query on a sizable table is a missing or wrong index causing a scan; adding an appropriate index (covering the filter, join, and sort columns) often fixes it outright. Third, I reduce what’s loaded: replace full-entity loading with a projection (Selectinto a DTO) so only needed columns are transferred and materialized, and addAsNoTrackingif it’s read-only so tracking overhead is removed. Fourth, I eliminate N+1 by loading related data in one query - eager loading withInclude/ThenInclude, or a single projected query - and useAsSplitQueryif multiple collection includes cause a row explosion. Fifth, I ensure large result sets are paginated (keyset pagination for large tables, since deep offset pagination is slow). For mass updates/deletes I use set-basedExecuteUpdate/ExecuteDeleteinstead of loading and saving each entity. Then I re-measure to confirm the fix and that I didn’t shift the problem. So the disciplined sequence is: capture the real SQL, analyze the execution plan and indexes, project and untrack the reads, fix N+1 with eager loading/projection, paginate, and re-measure - each step driven by the evidence of what the ORM actually emits and what the database actually does, because EF Core performance problems are almost always inefficient generated SQL, missing indexes, over-fetching, or N+1, all of which are only visible when you look rather than assume.

Principal Engineer Question

How do you scale EF Core data access for enterprise workloads processing millions of records?

At the scale of millions of records I combine efficient query design, database optimization, appropriate architecture, and specialized processing patterns, driven by continuous measurement. On query efficiency, the fundamentals compound at scale: project to only needed columns, useAsNoTrackingfor reads, eliminate N+1 with eager loading or projections, and never return unbounded sets - use keyset pagination. For mass data changes I use set-based operations (ExecuteUpdate/ExecuteDelete) and batched, throttled processing rather than loading and saving millions of entities, which would exhaust memory and flood the transaction log. On the database, indexing is decisive at this scale - the right indexes turn scans of millions of rows into seeks - so I design indexes to match the query patterns and validate with execution plans, and I consider partitioning very large tables. On architecture, I separate read and write paths: heavy reporting and analytics shouldn’t contend with transactional writes, so I use read replicas and/or a CQRS read model (denormalized, read-optimized) fed from the transactional store, and I cache frequently-read, slowly-changing reference data (in-memory or distributed) to keep it off the database entirely. For very large processing jobs I stream results (EF Core async streaming / no buffering the whole set) and run them as background/batch jobs rather than in request threads, processing in bounded batches with backpressure. I use connection pooling (automatic) and DbContext pooling for high-throughput request paths to cut per-request overhead. Where a relational store is the wrong fit for a workload - massive-scale key access, search, analytics - I use the right technology (NoSQL like Cosmos DB, a search engine, a data warehouse) rather than forcing everything through EF Core against one relational database. And throughout I measure - capturing SQL, reading plans, and monitoring database and application performance - so optimizations target real bottlenecks and regressions are caught. So scaling EF Core data access is not one trick but a combination: efficient projected/untracked/paginated queries, set-based bulk operations and batched background processing, decisive indexing and partitioning, read/write separation via replicas and CQRS read models, caching of hot reference data, streaming for huge reads, context/connection pooling, and polyglot persistence where appropriate - all guided by measurement - which lets a data layer handle millions of records while staying fast and stable, rather than the naive load-entities-and-save approach that works at thousands but collapses at millions.

8.6 Production Scenario

A banking reporting system slows as transaction history grows to hundreds of millions of rows. The team projects to read DTOs, disables tracking, adds composite indexes, switches to keyset pagination, moves heavy reporting to a read replica and a denormalized read model, caches hot reference data, and runs the largest jobs as batched background work - restoring performance and keeping reporting load off the transactional write path.

Chapter Revision Notes

  • Project, untrack reads, kill N+1, paginate (keyset), and index - the core EF Core optimizations.
  • Use set-based ExecuteUpdate/ExecuteDelete for bulk changes instead of per-entity loops.
  • Rely on connection pooling; use DbContext pooling for high-throughput paths.
  • Measure first: inspect generated SQL and execution plans before optimizing.
  • At huge scale, add read replicas, CQRS read models, caching, streaming, and batched background jobs.