📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is over-fetching in EF Core, and how does client evaluation make it worse? Explain selecting only the columns you need, keeping large blobs out of hot queries, what happens when AsEnumerable() or ToList() appears in the middle of a query, and how you would find these problems.

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.

Intermediate Theory Intermediate client-evaluation ef-core over-fetching projection query-performance sql-server

🎯 Key points

  • Column over-fetching: loading entire entities (all columns) when a few are used
  • Row over-fetching: loading rows that are then filtered or paged away in memory
  • Select projection sends only the listed columns; DTO projections are not tracked
  • Large nvarchar(max) / varbinary(max) columns cost LOB reads, network and memory on every row
  • Keep blobs out of hot queries: projection, table splitting, or a separate table / blob storage
  • Anything after AsEnumerable() / ToList() runs in memory; keep IQueryable composition in the data layer
  • EF Core 3+ throws for untranslatable expressions, except in the final Select
  • Detect with ToQueryString(), LogTo, and comparing columns and rows returned with what is used

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 in nvarchar(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 returns IEnumerable runs in memory. So db.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 final Select, and an explicit AsEnumerable() is taken as 'I meant that'.

The fixes are simple once you see them. I project with Select into 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 every Where, OrderBy and Take before the first materialisation. To find it, I read the SQL with ToQueryString() or the logs and compare the columns and rows returned with what the code uses. The mistake I see is adding AsEnumerable() to make an untranslatable query compile without noticing it now pulls the whole table."


Two kinds of over-fetching

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)

Where the query boundary is

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)

Production example

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.

🔍 What the interviewer is checking

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

  • Knows projection sends only the selected columns and skips tracking
  • Explains the EF Core 3 change: throw on untranslatable, client allowed in the final projection
  • Mentions large-value columns, LOB reads and table splitting or Blob Storage
  • Uses ToQueryString() or logs to check

Red flags

  • Uses AsEnumerable() or ToList() to fix translation errors
  • Believes EF Core only fetches the properties the code later reads
  • Returns entities from every endpoint by default

📚 Learn in depth

1. What a full entity load costs

SQL 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.

2. Projection SQL

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.

3. Keeping blobs out

  • Never select them in list queries; load them only on detail endpoints.
  • Table splitting: map 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.
  • Separate table or Blob Storage: for files, store them in Azure Blob Storage and keep the URL; the database stays small and backups faster.

4. How client evaluation works since EF Core 3

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.

5. Finding it

  • ToQueryString() on the IQueryable shows the SQL; if a filter you wrote is missing from the WHERE, it runs on the client.
  • EF Core command logs show the column list.
  • Application Insights shows long SQL dependencies with large result sets; the actual plan shows key lookups and LOB reads.
  • Memory: dotnet-counters shows high allocation rate and gen 2 or LOH growth when big strings or byte arrays are loaded.

Try it yourself

  1. Create a 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.
  2. Run both queries with SET STATISTICS IO ON and compare LOB logical reads.
  3. Write db.Orders.AsEnumerable().Where(...) and db.Orders.Where(...), print ToQueryString() for the second and watch the row count in the logs for the first.
  4. Map ProductContent with table splitting and confirm db.Products no longer selects the blob column.
  5. Watch dotnet-counters monitor System.Runtime while loading the entity version and note the allocation rate.

💻 Code

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]

⚠ Common mistakes

  • Mistake: Adding 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.
  • Mistake: Returning entities from list endpoints. Why it is wrong: every column, including large ones, is read, sent and tracked. Instead: project into a DTO with only the returned fields.
  • Mistake: Loading entities for a read-only list without 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.
  • Mistake: Storing files in 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.
  • Mistake: Returning 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.
  • Mistake: Assuming EF Core 3+ never evaluates on the client. Why it is wrong: the final Select and explicit AsEnumerable() still run in .NET. Instead: read the SQL with ToQueryString().
  • Mistake: Including a collection to compute a count. Why it is wrong: every child row is transferred to produce one number. Instead: project o.Lines.Count.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions projecting into DTOs Why: Checks the SQL and tracking difference between Include and Select and when Include is still right
    How to answer

    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.

    • Navigations used inside 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.

  2. When: Candidate mentions client evaluation in the final Select Why: Checks deeper knowledge of what LINQ expressions translate and how to inspect the SQL
    How to answer

    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.

    • It translates mapped properties, navigations, operators, aggregates, GroupBy, and known methods such as string.Contains, StartsWith, DateTime parts and EF.Functions.Like.
    • From EF Core 3.0 onwards (still true in EF Core 10), client evaluation is allowed only in the final Select. Anything untranslatable elsewhere throws an InvalidOperationException instead of silently loading the table.
    • I check the output with ToQueryString() or LogTo.

    The trade-off: LINQ is expressive, but you must know which C# your provider can turn into SQL.

  3. When: Candidate suggests AsEnumerable() to get past an exception Why: Checks they can fix an untranslatable query without moving the whole query to memory
    How to answer

    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().

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me