skip to content

SQL Translation & Splitting

How EF Core turns IQueryable into SQL: what runs on the server, client code only in the final projection, and single versus split queries. Interviewers probe it because bad translations load too much.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

6

In EF Core 10, what happens when a query calls a C# method EF cannot translate, inside Where versus inside the final Select?

level: middleimportance: must knowfreq 64%

answer

  1. server first, client only at the end
  2. top-level projection is the exception
  3. InvalidOperationException: could not be translated
  4. AsEnumerable / AsAsyncEnumerable as explicit switch
  5. thrown when the query runs, not when built

basics

~20 s

Inside Where, EF Core throws an InvalidOperationException saying the expression could not be translated. Inside the final Select it fetches the needed columns and runs the method on the client: only the top-level projection may be client-evaluated.

solid answer

~50 s

EF Core translates as much of the query as it can into SQL and allows client code in exactly one place: the **top-level projection**, the last `Select`. There it reads the columns the C# method needs and calls the method on each materialized row. Anywhere else — `Where`, `OrderBy`, a join key, an aggregate — an untranslatable call makes the query fail with an `InvalidOperationException` whose message says the expression could not be translated and suggests `AsEnumerable`, `AsAsyncEnumerable`, `ToList` or `ToListAsync`. The exception surfaces when the query is compiled on first execution, such as at `ToListAsync()`, not when the `IQueryable` is composed. The fix is to rewrite the filter in translatable terms, or to switch to client evaluation **explicitly** after a server-side filter that already shrank the rows, knowing every row it lets through crosses the wire.

code

csharp · 8 lines
csharp
// Projection-only client code: OK
var cards = await db.Projects
    .Where(p => p.IsActive)
    .Select(p => new { p.Name, Health = Score(p.OpenItems, p.LateItems) })
    .ToListAsync();

static string Score(int open, int late) =>
    late == 0 ? "green" : late * 4 < open ? "amber" : "red";

go deeper

for a junior

Remember the rule: only the last Select may contain your own C# methods; a custom method inside Where throws an exception saying it could not be translated.

for a middle

Explain that translation happens at execution, how EF fetches only the needed columns for a client projection, and how AsEnumerable or AsAsyncEnumerable moves the boundary deliberately.

for a senior

Show you treat every explicit client switch as a data-volume decision, check generated SQL in review, and know why instance methods in projections are rejected because of the query cache.

for a principal

Frame the strict rule as a trade, loud failures over silent full-table reads, and set team rules for when an explicit client switch is acceptable.

## Where EF Core draws the line EF Core turns a LINQ expression tree into SQL. Everything it can map to SQL runs on the **database server**; values captured from your C# code, such as a local `projectId`, become SQL parameters. A call to one of your own C# methods has no SQL equivalent, because the provider cannot see inside the method body. The rule is strict: - **Top-level projection (the final `Select`)**: client evaluation is allowed. EF selects the columns the method needs, materializes each row and calls the method in .NET. - **Anywhere else** (`Where`, `OrderBy`, `GroupBy` keys, join keys, aggregates, a `Select` that is followed by more operators): EF throws an `InvalidOperationException`. Early EF Core releases silently evaluated untranslatable filters on the client and only logged a warning, which meant a dashboard filter could pull a whole table into memory unnoticed. The exception replaced that silent behaviour long ago, and EF Core 10 keeps it. ## The project dashboard example A project-tracking dashboard lists overdue work items and shows the owner's initials: ```csharp static string Initials(string fullName) => string.Concat(fullName.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(p => p[0])); // OK: the helper runs on the client, in the final Select var rows = await db.WorkItems .Where(w => w.ProjectId == projectId && w.DueDate < today) .Select(w => new { w.Title, Owner = Initials(w.Owner.FullName) }) .ToListAsync(); // Throws InvalidOperationException when ToListAsync runs var mine = await db.WorkItems .Where(w => Initials(w.Owner.FullName) == "AK") .ToListAsync(); ``` In the first query the `WHERE` clause, the join to the owner and the column list all run in SQL; only `Initials` runs in .NET on the rows that come back. In the second query the filter itself needs `Initials`, so EF would have to fetch every work item to apply it. It refuses, and the message reads: *"The LINQ expression '...' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'."* ## When the exception appears Composing an `IQueryable` does not run anything. Translation happens when the query is **compiled**, which EF does the first time it is executed (`ToListAsync`, `FirstOrDefaultAsync`, `CountAsync`, `await foreach`, or `ToQueryString`). That is why a bad query can pass a code review and fail on the first request that reaches it, and why an integration test that actually executes each query is worth having. ## Fixing an untranslatable filter 1. **Rewrite it in translatable terms.** Store or compute the value in a column, compare on a property, or use a function the provider maps (`string.StartsWith`, `EF.Functions.Like`, date parts). 2. **Filter on the server first, then switch explicitly.** Insert `AsAsyncEnumerable()` (streaming) or `ToListAsync()` (buffering) after the server-side `Where`, and apply the C# method to the much smaller result: ```csharp await foreach (var w in db.WorkItems .Where(w => w.ProjectId == projectId) .AsAsyncEnumerable()) { if (Initials(w.Owner.FullName) == "AK") { /* ... */ } } ``` The explicit switch is a statement that you accept the transfer cost. It is fine for a few hundred rows and a defect for a table that grows. ## A trap inside the allowed case Client evaluation in the projection still has a cost model: | Shape | What happens | |---|---| | Static helper in the final `Select` | Works; EF fetches only the columns the helper reads | | Instance method of a service in the final `Select` | EF refuses, because the compiled query would capture the instance as a constant and keep it alive in the query cache | | Helper in `Where` / `OrderBy` | `InvalidOperationException` — could not be translated | | `AsEnumerable()` before the helper | Allowed; everything before it runs in SQL, everything after it in .NET | The instance-method case exists because EF caches compiled queries. A captured service instance (perhaps holding a `DbContext`) would never be garbage-collected, so EF throws and asks you to make the method static or to pass the data it needs as arguments. ## What interviewers listen for - The rule names the **final projection**, not "the end of the query"; a `Select` followed by `Where` is not top-level. - The candidate knows it is an exception at execution time, not a warning. - The candidate checks the generated SQL, rather than trusting that a query which runs also runs on the server.

  • Why does EF Core refuse a projection that calls an instance method on an injected service, even though it is in the final Select?
    EF caches the compiled query. Calling an instance method would put the service instance into the cached delegate as a constant, so it, and anything it references such as a `DbContext`, could never be collected. EF throws instead and asks you to make the method static or pass the values it needs as arguments, which become parameters.
  • What is the difference between inserting AsAsyncEnumerable() and ToListAsync() before client-side code?
    Both end the server-side part of the query. `AsAsyncEnumerable()` streams rows one at a time while you iterate, holding the reader open; `ToListAsync()` buffers every row into a `List<T>` first. Streaming uses less memory for one pass; buffering frees the connection sooner and lets you iterate more than once.

  • EF Core silently pulls the whole table and filters it in memory.
  • Client evaluation is allowed anywhere as long as the method is static.
  • The translation error appears when the IQueryable is built.
  • Calling AsNoTracking makes an untranslatable Where work.
  • A method used in the last Select runs inside the database.
open as a page

An EF Core 10 project dashboard loads each project's work items and members in one query and has become slow; how do AsSplitQuery and QuerySplittingBehavior help, and what do they cost?

level: seniorimportance: must knowfreq 55%

basics

~10 s

Loading two sibling collections in one SQL statement multiplies rows per project. AsSplitQuery, or UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) globally, sends one statement per collection instead, at the cost of extra round trips and no single-snapshot consistency.

open as a page

In EF Core, how do you see the SQL a LINQ query will send without running it, and where does ToQueryString fall short?

level: juniorimportance: should knowfreq 42%

basics

~20 s

Call ToQueryString() on the IQueryable before executing it: it compiles the query and returns the SQL with its parameter values, for debugging only. It cannot show terminal operators like CountAsync, and for a split query it shows just the first statement.

open as a page

In EF Core 10, which GroupBy queries translate to a SQL GROUP BY, and what happens when a query returns the groups themselves?

level: middleimportance: should knowfreq 44%

basics

~20 s

GroupBy followed by a Select of the key and aggregates such as Count or Sum becomes GROUP BY, and an aggregate filter becomes HAVING. A query ending in GroupBy is sent as an ordered SELECT and grouped on the client.

open as a page

In EF Core 10, how do you write a SQL LEFT JOIN in LINQ, and how did you have to express it before .NET 10?

level: middleimportance: should knowfreq 34%

basics

~20 s

Call the .NET 10 LeftJoin operator in method syntax, outer.LeftJoin(inner, outerKey, innerKey, (o, i) => ...), and EF Core 10 emits LEFT JOIN. Before .NET 10 you chained GroupJoin, SelectMany and DefaultIfEmpty in one exact shape.

open as a page

After upgrading to EF Core 10, a query using ids.Contains(w.ProjectId) sends different SQL; what changed, and how do EF.Constant, EF.Parameter and UseParameterizedCollectionMode control it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

EF Core 10 translates a captured collection into several scalar parameters, IN (@ids1, @ids2, ...), instead of EF 8-9's single JSON array parameter. UseParameterizedCollectionMode sets the default per context; EF.Constant, EF.Parameter and EF.MultipleParameters override it for one query.

open as a page