Volume 3 · Chapter 3 — Entity Framework Core and Data Access Engineering
LINQ Translation and Query Optimization
3.1 Introduction
In EF Core, LINQ queries are not run in memory - they are translated into database queries. Understanding this translation is critical, because the same LINQ can produce efficient SQL or a performance disaster depending on how it is written. The two most important concepts are the difference betweenIQueryableandIEnumerable, and the N+1 query problem - the single most common EF Core performance bug.
3.2 IQueryable vs IEnumerable
This distinction determineswherea query runs.IQueryableoperations are captured as expression trees and translated to SQL, so filtering and projection happen in the database.IEnumerableoperations run in application memory after data is loaded. Accidentally switching toIEnumerabletoo early (for example calling.ToList()or.AsEnumerable()before filtering) pulls the whole table into memory and filters there - a catastrophic mistake on a large table.
// GOOD - filtering happens in SQL (IQueryable):
var active = await db.Customers.Where(c => c.IsActive).ToListAsync(ct); // WHERE IsActive=1
// BAD - loads ALL customers into memory, then filters in C# (IEnumerable):
var active2 = db.Customers.ToList().Where(c => c.IsActive).ToList(); // whole table transferred!
3.3 Projection: Select Only What You Need
Loading full entities when you need a few fields wastes database transfer, memory, and time. Projecting withSelectinto a DTO makes EF Core generate SQL that selects only those columns - one of the highest-value optimizations, and it implicitly avoids tracking overhead too.
var rows = await db.Customers
.Select(c => new CustomerRow(c.Id, c.Name)) // SELECT Id, Name (not SELECT *)
.ToListAsync(ct);
3.4 The N+1 Query Problem
N+1 is the classic EF Core trap: one query loads a list, then loading each item’s related data triggers an additional query per item - 1 + N round trips where 1 or 2 would do. It devastates performance at scale because each round trip has fixed latency. The fix is to load related data in one query withInclude(eager loading) or, better, a projection.
sequenceDiagram
autonumber
participant App as App
participant DB as Database
Note over App,DB: N+1 (bad)
App->>DB: SELECT customers
DB-->>App: 100 customers
loop for each customer
App->>DB: SELECT orders WHERE CustomerId = ?
end
Note over App,DB: Fixed - one query
App->>DB: SELECT customers JOIN orders (Include/projection)
DB-->>App: all data in one round trip
// N+1: one query for customers, then one per customer for orders (deadly at scale)
var customers = await db.Customers.ToListAsync(ct);
foreach (var c in customers)
c.OrderCount = (await db.Orders.Where(o => o.CustomerId == c.Id).ToListAsync(ct)).Count;
// Fixed: single projected query
var summary = await db.Customers
.Select(c => new { c.Id, c.Name, OrderCount = c.Orders.Count }) // one query with a subquery/join
.ToListAsync(ct);
3.5 Query Splitting, Compiled Queries, and Indexes
When youIncludemultiple collections, a single query produces a large cartesian join (row explosion);AsSplitQueryruns separate optimized queries instead. Frequently-executed queries can be pre-compiled withEF.CompileAsyncQueryto cut translation overhead. And no LINQ optimization helps if the database lacks the right indexes - application and database optimization must work together.
What is the N+1 query problem in EF Core, and how do you fix it?
The N+1 problem is issuing one query to load a collection of entities and then one additional query per entity to load its related data - so loading N customers and then their orders becomes 1 + N queries instead of 1 or 2. It’s easy to introduce accidentally: iterating a loaded list and accessing a navigation property that triggers a separate database round trip per item (via lazy loading, or by explicitly querying related data inside a loop). It destroys performance at scale because each query has fixed network and execution latency, so N=1000 means a thousand round trips where one well-shaped query would suffice - a request that should take milliseconds takes seconds. The fixes all come down to fetching the related data in a single (or a small fixed number of) query rather than per-item. Eager loading withInclude(andThenInclude) tells EF Core to join and load the related data along with the parent in one query. Better still for read scenarios is projection:Selectinto a DTO that pulls exactly the related data you need (e.g. a count or specific fields), letting EF Core generate one efficient query with the necessary joins/subqueries and transferring only what’s needed. For multiple collection includes I useAsSplitQueryto avoid a cartesian row explosion while still bounding the number of queries. The key is to detect it - which requires looking at the generated SQL / query counts (logging EF’s queries in development makes N+1 obvious) - and then reshape the query to load related data in one round trip. Preventing it is largely about disabling lazy loading (so accidental per-item loads don’t happen silently), using explicit eager loading or projection, and reviewing the SQL EF Core emits. N+1 is the single most common EF Core performance bug, and recognizing and fixing it - one round trip instead of N - is essential data-access engineering.
What is the difference between IQueryable and IEnumerable in EF Core, and why does it matter?
The difference iswherethe query executes, and getting it wrong is a catastrophic performance bug. AnIQueryable<T>(what aDbSetis) represents a query that hasn’t run yet; its operators (Where, Select, OrderBy, etc.) build up an expression tree that EF Core translates into SQL and executes in the database, so filtering, projection, sorting, and paging happen server-side and only the final result is transferred. AnIEnumerable<T>represents an in-memory sequence; its LINQ operators (LINQ-to-Objects) execute in application memory. The moment you convert anIQueryabletoIEnumerable- by callingToList(),AsEnumerable(), or iterating - EF Core executes the query as it stands and materializes the results, and any LINQ you apply afterward runs in memory, not in SQL. This matters enormously: if you call.ToList()or.AsEnumerable()before applying aWherefilter, EF Core loads the entire table into memory and then filters in C#, which on a large table transfers and materializes millions of rows to return a handful - a disaster. Whereas keeping the query asIQueryableuntil all filtering, projection, and paging is expressed means EF Core generates one efficient SQL statement that does the work in the database and returns only what you need. So the rule is to compose your full query onIQueryable(so it all translates to SQL) and only materialize (ToListAsync) at the very end, and to be extremely careful not to prematurely switch to in-memory evaluation. It also explains why an operation EF can’t translate to SQL forces client evaluation - modern EF Core throws rather than silently pulling data into memory, precisely to prevent the accidental full-table-load this distinction can cause. Understanding IQueryable vs IEnumerable is fundamental to writing EF Core queries that run in the database rather than accidentally in app memory.
A transaction-search API became slow as the table grew from millions to hundreds of millions of rows. How do you troubleshoot and fix it?
At hundreds of millions of rows, small inefficiencies become fatal, so I troubleshoot by looking at the actual database behavior and fix both the query shape and the database design. First I capture the generated SQL for the slow search (EF Core query logging) so I see exactly what runs, then I take those queries to the database and examine their execution plans, which almost always reveal the culprit at this scale: table or index scans over a huge table because the search’s filter and sort columns aren’t properly indexed. So the primary fix is indexing - ensuring the columns the search filters, joins, and orders by are covered by appropriate indexes (composite indexes matching the query’s predicates and sort order, and covering indexes where beneficial), which turns scans of hundreds of millions of rows into targeted seeks. Alongside that I fix the query shape: replace loading full tracked entities with projections that select only the columns the search results need (dramatically less data transferred and materialized), addAsNoTrackingsince search is read-only, and eliminate any N+1 patterns by loading related data in one query. Critically for a large table, pagination must be efficient - offset pagination (Skip/Take) degrades badly deep into a huge result set because the database must count through all skipped rows, so I move to keyset (seek) pagination using an indexed key (e.g. WHERE Id < lastSeenId ORDER BY Id, page size Take), which stays fast regardless of depth. I also constrain the search sensibly - require or default to selective filters (date ranges, account) so queries hit indexes and don’t scan the whole table, and enforce a maximum page size. If the search still can’t meet latency against the transactional table, I consider a read- optimized structure - a search index (e.g. a dedicated search engine or a denormalized read model), or a read replica - so heavy search load doesn’t hit the write path. I validate each change by re-checking the execution plan and measuring latency at production scale. The disciplined path is: capture the real SQL, read the execution plans, add the right indexes, project and untrack the reads, use keyset pagination, keep searches selective, and offload to a purpose-built read model if needed - all driven by evidence from the generated SQL and plans, because at this data volume the database’s index and query-plan behavior is what determines performance, and that’s only visible when you inspect what the ORM actually emits.
3.6 Production Scenario
A transaction-search API slows as the table grows to hundreds of millions of rows. Capturing the SQL and reading execution plans reveals scans from missing indexes, full-entity loading, and deep offset pagination. The team adds composite indexes on the filter/sort columns, replaces entity loading with projections andAsNoTracking, removes an N+1, and switches to keyset pagination - restoring fast responses at scale, with a dedicated search index for the heaviest queries.
Chapter Revision Notes
- IQueryable translates to SQL (database-side); switching to IEnumerable early loads everything into memory.
- Project with Select to fetch only needed columns - high-value and avoids tracking.
- N+1 is the most common EF Core bug - fix with Include (eager) or a single projected query.
- Use AsSplitQuery for multiple collection includes; compiled queries for hot queries.
- Application query optimization must be paired with proper database indexes and keyset pagination at scale.