Covers column and row over-fetching in EF Core, large blob columns and table splitting, client evaluation through AsEnumerable or ToList in the middle of a query, and how to detect both in the generated SQL.
Over-fetching is loading more than the use case needs: whole entities when the screen uses three columns, or rows you then filter away in memory. Client evaluation makes it worse: everything after AsEnumerable() or ToList() runs in .NET, so a Where or OrderBy placed after it downloads the whole set first. Since EF Core 3, untranslatable expressions throw instead of silently running on the client, except in the final Select, but an explicit AsEnumerable() still moves the work to memory. I fix it by projecting with Select into a DTO, keeping large nvarchar(max) or varbinary(max) columns out of list queries (projection, table splitting or a separate table), and keeping every filter before materialisation. I find it with ToQueryString() and logs. The trade-off: projections mean more DTO types, but each query moves only the data it uses.
"Over-fetching is when the query brings back more than the code uses. The common case is
db.Products.Where(...).ToListAsync()for a list page that shows the name and price, but the entity has a description innvarchar(max), a JSON spec column and an image. SQL Server reads all of it, sends it over the network, and EF Core materialises and tracks it. On a list of a few hundred rows that can be megabytes per request for a page that needs a few kilobytes.Client evaluation is the other half. Everything up to the point where you enumerate is translated to SQL; everything after
AsEnumerable(),ToList()or a method that returnsIEnumerableruns in memory. Sodb.Orders.AsEnumerable().Where(o => o.Total > 100)downloads every order and filters in .NET. EF Core 3 and later throws when it can't translate an expression, which stopped the silent version of this, but it still allows client code in the finalSelect, and an explicitAsEnumerable()is taken as 'I meant that'.The fixes are simple once you see them. I project with
Selectinto a DTO with only the columns the endpoint returns, which also skips change tracking. I keep large columns out of hot queries: either just never project them, or use table splitting so the blob lives on a separate entity that is only loaded on the detail page, or move files to Blob Storage and keep a URL. And I keep everyWhere,OrderByandTakebefore the first materialisation. To find it, I read the SQL withToQueryString()or the logs and compare the columns and rows returned with what the code uses. The mistake I see is addingAsEnumerable()to make an untranslatable query compile without noticing it now pulls the whole table."
| Kind | Example | Fix |
|---|---|---|
| Too many columns | ToListAsync() on an entity with nvarchar(max) and varbinary(max) columns |
Select only the needed columns |
| Too many rows | ToList() then Where, or no Take on a list |
Filter and page in the query before materialising |
| Related data not used | Include(o => o.Lines) to show a count |
Select(o => o.Lines.Count) |
| Code | Where it runs |
|---|---|
db.Orders.Where(o => o.Total > 100) |
SQL (WHERE [o].[Total] > 100.0) |
db.Orders.AsEnumerable().Where(o => o.Total > 100) |
Client: every order downloaded |
db.Orders.Where(o => MyHelper(o)) |
Throws InvalidOperationException (cannot translate) |
db.Orders.Select(o => new { o.Id, Label = Format(o) }) |
Columns from SQL, Format runs on the client (allowed in final projection) |
A product search API [in a system I worked on] returned entities with an nvarchar(max) description and a 200 KB image column. Each page of 50 results moved about 10 MB from Azure SQL. A projection with six columns cut it to about 15 KB per page and p95 from about 1.2 s to 80 ms; the images moved to Blob Storage behind a CDN.
Checks that the candidate understands what columns and rows EF Core actually fetches, where the SQL boundary of a query is, and how to keep work in the database.
Green flags
ToQueryString() or logs to checkRed flags
AsEnumerable() or ToList() to fix translation errorsSQL Server network EF Core
────────── ─────── ───────
read data pages + LOB pages -> every column -> allocate entity,
(off-row LOB reads for per row copy every value,
max columns) snapshot for tracking
Large-value columns (nvarchar(max), varbinary(max)) over 8,000 bytes are stored off-row in LOB pages, so reading them costs extra logical reads per row. A covering index also can't include them efficiently, so SELECT * forces a lookup into the clustered index for every row. Tracking adds a snapshot copy of every property, roughly doubling the memory for each entity.
db.Products.Where(p => p.CategoryId == id).Select(p => new ProductRow(p.Id, p.Name, p.Price))
SELECT [p].[Id], [p].[Name], [p].[Price]
FROM [Products] AS [p]
WHERE [p].[CategoryId] = @id
Three columns means a narrow index (CategoryId) INCLUDE (Name, Price) can cover the query with no lookups. Projected results are not tracked, even without AsNoTracking(), unless the projection contains entity instances.
Product and ProductContent to the same table with a shared key, so db.Products reads only the small columns and ProductContent is loaded when needed.The query pipeline translates the expression tree up to the first point that requires IEnumerable. Before EF Core 3, untranslatable parts silently ran on the client after downloading rows. Since 3.0, EF Core throws InvalidOperationException: The LINQ expression ... could not be translated, with one exception: the top-level Select, where client methods are allowed because they only shape rows already fetched. Calling AsEnumerable() or ToList() deliberately switches to LINQ to Objects, so anything after it is client-side with no warning.
ToQueryString() on the IQueryable shows the SQL; if a filter you wrote is missing from the WHERE, it runs on the client.Product entity with a 100 KB varbinary(max) column, load 500 rows as entities and as a projection, and compare duration and allocations with BenchmarkDotNet's MemoryDiagnoser.SET STATISTICS IO ON and compare LOB logical reads.db.Orders.AsEnumerable().Where(...) and db.Orders.Where(...), print ToQueryString() for the second and watch the row count in the logs for the first.ProductContent with table splitting and confirm db.Products no longer selects the blob column.dotnet-counters monitor System.Runtime while loading the entity version and note the allocation rate.Over-fetching and client evaluation, then the projection and table-splitting fixes.
namespace Shop.Catalogue;
using Microsoft.EntityFrameworkCore;
public sealed record ProductRow(int Id, string Name, decimal Price);
public sealed class CatalogueQueries(ShopDbContext db)
{
// BAD: AsEnumerable() downloads every product with every column, then filters and sorts in memory.
public List<Product> SearchSlow(int categoryId) =>
db.Products.AsEnumerable()
.Where(p => p.CategoryId == categoryId)
.OrderBy(p => p.Name)
.Take(50)
.ToList();
// GOOD: filter, sort, page and pick columns in SQL; untracked by nature.
public Task<List<ProductRow>> SearchAsync(int categoryId, CancellationToken ct) =>
db.Products
.Where(p => p.CategoryId == categoryId)
.OrderBy(p => p.Name).ThenBy(p => p.Id)
.Take(50)
.Select(p => new ProductRow(p.Id, p.Name, p.Price))
.ToListAsync(ct);
}
// Table splitting: the large content lives on its own entity mapped to the same table.
public sealed class Product
{
public int Id { get; set; }
public int CategoryId { get; set; }
public required string Name { get; set; }
public decimal Price { get; set; }
public ProductContent? Content { get; set; }
}
public sealed class ProductContent
{
public int Id { get; set; }
public string Description { get; set; } = ""; // nvarchar(max)
public byte[]? Thumbnail { get; set; } // varbinary(max)
}
public sealed class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Product> b)
{
b.ToTable("Products");
b.Property(p => p.Name).HasMaxLength(200);
b.Property(p => p.Price).HasPrecision(18, 2);
b.HasOne(p => p.Content).WithOne().HasForeignKey<ProductContent>(c => c.Id);
b.Navigation(p => p.Content).IsRequired(false);
}
}
public sealed class ProductContentConfiguration : IEntityTypeConfiguration<ProductContent>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<ProductContent> b) =>
b.ToTable("Products"); // same table: db.Products no longer reads Description or Thumbnail
}
-- SQL for SearchAsync
SELECT TOP(@p) [p].[Id], [p].[Name], [p].[Price]
FROM [Products] AS [p]
WHERE [p].[CategoryId] = @categoryId
ORDER BY [p].[Name], [p].[Id]
AsEnumerable() to get past a translation exception. Why it is wrong: everything after it runs in memory, so the whole table may be downloaded. Instead: rewrite the expression so it translates, or apply all filters first and only use client code in the final projection.AsNoTracking(). Why it is wrong: every entity gets a change-tracking snapshot, roughly doubling memory and adding identity-map work. Instead: project into a DTO (DTO projections are never tracked, so AsNoTracking() is redundant there) or add AsNoTracking() when you must return entities. Note that a projection that contains entity instances, such as Select(o => new { o, o.Customer }), is tracked.varbinary(max) and reading them in list queries. Why it is wrong: LOB reads and network transfer dominate the request. Instead: keep files in Blob Storage or load them only on a detail endpoint.IEnumerable<T> from a repository method that wraps a query. Why it is wrong: callers' Where and Take then run on the client. Instead: return a materialised, already-filtered list or keep IQueryable inside the data layer.Select and explicit AsEnumerable() still run in .NET. Instead: read the SQL with ToQueryString().o.Lines.Count.Over-fetching is cheap to prevent and expensive to find later, because it hides inside healthy-looking query counts. My rule is that read endpoints project and write paths load aggregates, and that large columns never sit on an entity used in list queries. When a table already has a blob column that half the code loads, table splitting is the least disruptive fix because the schema stays the same.
The other design rule is where IQueryable stops. Inside the data layer I compose filters, sorting, paging and the projection on IQueryable so the database does the work; the method then returns a materialised list or a paged result, not IEnumerable over a live query and not IQueryable to controllers. That keeps the SQL boundary in one place, so a later Where added by a caller cannot quietly turn into an in-memory filter over a whole table, and it keeps the query reviewable. I measure with bytes and rows per request, not just duration, because over-fetching grows with data volume and payload size.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Select projection |
Read endpoints | More DTO types | Updating the entity |
| Table splitting | Existing table with large columns | Extra entity type and mapping | Small tables where the columns are always needed |
| Separate table or Blob Storage | Files and documents | Migration and extra storage | Small values queried with the row |
Client code in final Select |
Formatting after fetch | Runs per row in .NET | Filtering or sorting (must be in SQL) |
For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.
Select are joined automatically; no Include is needed (and Include is ignored there).Include is still right when I load an aggregate to modify and save it, because I need tracked entities.The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.
EF Core takes the expression tree built by IQueryable operators, normalises it, translates it into a SQL expression tree using the provider's method translators (so SQL Server, PostgreSQL and SQLite produce different SQL and support different methods), and generates SQL text. The compiled result is cached by query shape, and captured variables become parameters.
GroupBy, and known methods such as string.Contains, StartsWith, DateTime parts and EF.Functions.Like.Select. Anything untranslatable elsewhere throws an InvalidOperationException instead of silently loading the table.ToQueryString() or LogTo.The trade-off: LINQ is expressive, but you must know which C# your provider can turn into SQL.
Read the message: it names the sub-expression EF Core couldn't translate (usually a C# method, an unmapped property or a complex string operation). Then rewrite that part in SQL-compatible terms: simpler LINQ with plain operators and ranges, EF.Functions.Like, built-in mapped methods, a mapped computed column, or a database function mapped with HasDbFunction. Since EF Core 3.0, client code is allowed only in the final Select; anything you place after AsEnumerable() also runs in memory, so do that only after the filters have run in SQL. Confirm the fix with ToQueryString().
Last updated 23 Nov 2026.