In EF Core 10, what happens when a query calls a C# method EF cannot translate, inside Where versus inside the final Select?
answer
- server first, client only at the end
- top-level projection is the exception
- InvalidOperationException: could not be translated
- AsEnumerable / AsAsyncEnumerable as explicit switch
- thrown when the query runs, not when built
basics
~20 sInside 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 sEF 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// 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
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.
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.
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.
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.