Covers EF Core's query pipeline, which LINQ constructs and methods translate to SQL Server, the final-projection client-evaluation rule, translation exceptions and how to inspect SQL with ToQueryString() and LogTo.
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.
"When I enumerate an EF Core query, the provider gets the expression tree that the
Queryableoperators built. EF Core first preprocesses it: it expands navigations into joins, inlines query filters and normalises things likeAnyandContains. Then the relational layer translates each node into a SQL expression, using method-call translators the SQL Server provider registers, sostring.StartsWithbecomesLIKE N'abc%',DateTime.YearbecomesDATEPART(year, ...), andEF.Functions.Likemaps straight through. Finally it generates the SQL text and a shaper that turns rows into objects. That whole compiled query is cached keyed by the tree's shape, and captured variables become parameters, so the same query with a different customer id reuses both EF Core's cache and SQL Server's plan.What doesn't translate is anything EF Core can't see into: my own C# methods, unmapped properties, most
ToString()formats, or complex in-memory objects in the predicate. Since EF Core 3.0 the rule is strict. Client code is allowed only in the top-level projection, the finalSelect, because by then the rows are already filtered. Anywhere else, EF Core throwsInvalidOperationException: The LINQ expression ... could not be translated. Before 3.0 it silently pulled the table into memory, which is why old blog posts show surprising behaviour.The mistake I see is guessing at the SQL. I call
ToQueryString()in a test or the debugger, and in development I useLogToor theMicrosoft.EntityFrameworkCore.Database.Commandlog category, withTagWithso I can find the query in Query Store later. If I can't read the SQL, I don't ship the query."
| LINQ / C# | SQL |
|---|---|
Where(o => o.Total > x) |
WHERE [o].[Total] > @x |
o.Name.Contains(term) |
[o].[Name] LIKE N'%' + @term + N'%' (with escaping) |
o.Name.StartsWith(term) |
LIKE @term + N'%' (sargable) |
ids.Contains(o.Id) |
IN (@ids1, @ids2, ...) in EF Core 10 by default |
o.PlacedAt.Year == 2026 |
DATEPART(year, [o].[PlacedAt]) = 2026 |
GroupBy(...).Select(g => new { g.Key, Count = g.Count() }) |
GROUP BY ... COUNT(*) |
Any() |
EXISTS (...) / CASE WHEN EXISTS |
LeftJoin(...) (.NET 10) |
LEFT JOIN |
| Expression | Why |
|---|---|
Your own method IsVip(o) |
EF Core cannot see inside compiled IL |
Unmapped ([NotMapped]) property |
No column to read |
string.Format, most ToString("format") |
No reliable SQL equivalent |
A list of complex objects in Contains |
Only primitive collections become parameters |
| Tool | When |
|---|---|
query.ToQueryString() |
Unit tests, debugger, code review |
optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information) |
Local development |
Microsoft.EntityFrameworkCore.Database.Command log category |
Hosted environments (Information level) |
TagWith("Orders/Search") |
Find the query in Query Store or Application Insights |
| Application Insights dependency telemetry | Production SQL text and duration |
A report filtered with o.PlacedAt.ToString("yyyy-MM") == month. On EF Core 2 it silently loaded about [1.2 million] rows per call; after the upgrade to 3.x it threw. We replaced it with a date range (o.PlacedAt >= start && o.PlacedAt < end), which translated to a sargable WHERE and dropped the query from [8 s] to [40 ms] using the existing index.
Checks that the candidate understands EF Core as a SQL generator with rules, not magic, and knows how to see and fix what it produces.
Green flags
ToQueryString(), LogTo or TagWith without prompting.Red flags
ToList().LINQ expression tree (from Queryable operators)
│
▼ 1. Parameter extraction: closure fields -> parameters, tree is now cacheable
▼ 2. Cache lookup by tree shape (hit -> skip to execution)
▼ 3. Preprocessing: navigation expansion, query filters, normalisation
▼ 4. Translation: QueryableMethodTranslatingExpressionVisitor
│ + provider method-call translators (SqlServerStringMethodTranslator, ...)
▼ 5. Post-processing: null semantics, SQL tree optimisation
▼ 6. SQL generation (QuerySqlGenerator) + shaper (materialiser) compiled to a delegate
▼
Execution: DbCommand with parameters -> DbDataReader -> shaper -> objects
Steps 3–6 are the expensive part (often milliseconds). The cache means they run once per query shape. This is also why building expression trees with constants that change (for example Expression.Constant(userId)) is bad: each value is a new shape, a cache miss, and a new SQL Server plan.
var id = 42;
db.Orders.Where(o => o.CustomerId == id); // closure -> @id parameter
db.Orders.Where(o => o.CustomerId == 42); // literal -> inlined 42
Parameters let SQL Server reuse one plan. You can force a value to be inlined with EF.Constant(x), or force a parameter with EF.Parameter(x), which helps in rare plan-quality cases.
C# says null == null is true; SQL says NULL = NULL is unknown. EF Core rewrites comparisons on nullable columns to preserve C# semantics:
-- o.Region == region (both nullable)
WHERE [o].[Region] = @region OR ([o].[Region] IS NULL AND @region IS NULL)
That extra OR can hurt index use. Declaring columns NOT NULL where possible, or UseRelationalNulls() if you accept SQL semantics, removes it.
SELECT [o].[Id], [o].[Total], [o].[PlacedAt] <- translated part
C#: new Label(Format(o.Id, o.Total)) <- runs per row, after fetch
EF Core splits the top-level Select into the columns it needs (translated) and the client function (run in the shaper). It is safe because filtering and paging already happened in SQL. It becomes risky only if the client function is called on huge result sets, or captures a DbContext (EF Core warns about this).
The exception message shows the failing sub-tree. Typical fixes:
| Cause | Fix |
|---|---|
| Custom C# method | Inline its logic as an expression, or use HasDbFunction to map a SQL function |
| Reusable derived value | Mapped computed column (HasComputedColumnSql) |
| Pattern matching | EF.Functions.Like |
| Collation-specific comparison | EF.Functions.Collate |
EF Core 8 and 9 sent ids.Contains(o.Id) as one JSON parameter unpacked with OPENJSON. EF Core 10 changed the default to multiple scalar parameters (IN (@ids1, @ids2, ...)) with padding so similar sizes share a plan, which gives SQL Server better cardinality estimates. It is a listed breaking change; for very large lists you can configure the translation mode globally or per query (EF.Constant / EF.Parameter).
ToQueryString() on five queries: a Contains, a StartsWith, a GroupBy, an Any and a date-part filter. Compare the SQL.Where and read the exception; then move it into the final Select.Where(o => o.CustomerId == id) with Where(o => o.CustomerId == 42) in the log and look for @__id_0.IS NULL branch; then make the column required and compare.TagWith("demo"), run the query and find the comment in SQL Server's Query Store or sys.dm_exec_query_stats.Inspecting translation and fixing an untranslatable predicate.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public sealed record MonthlyOrder(int Id, decimal Total, string Label);
public sealed class ReportQueries(ShopDbContext db)
{
// Throws: ToString("yyyy-MM") is not translatable inside Where.
public IQueryable<Order> Broken(string month) =>
db.Orders.Where(o => o.PlacedAt.ToString("yyyy-MM") == month);
// Translates: a half-open date range is sargable and uses an index on PlacedAt.
public Task<List<MonthlyOrder>> ForMonthAsync(int year, int month, CancellationToken ct)
{
var start = new DateTimeOffset(year, month, 1, 0, 0, 0, TimeSpan.Zero);
var end = start.AddMonths(1);
return db.Orders
.TagWith("Reports/ForMonth") // shows up as a SQL comment
.Where(o => o.PlacedAt >= start && o.PlacedAt < end)
.OrderBy(o => o.PlacedAt)
// Final projection: Describe() is client code, allowed only here.
.Select(o => new MonthlyOrder(o.Id, o.Total, Describe(o.Total)))
.ToListAsync(ct);
}
private static string Describe(decimal total) => total > 1000m ? "Large" : "Standard";
}
// In a test or the debugger: see the SQL without running it.
var sql = db.Orders.Where(o => o.Total > 100).OrderBy(o => o.Id).ToQueryString();
// Development logging (Program.cs)
builder.Services.AddDbContext<ShopDbContext>(o => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
.LogTo(Console.WriteLine, LogLevel.Information));
-- Reports/ForMonth
SELECT [o].[Id], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end
ORDER BY [o].[PlacedAt]
Where on the client. Why it is wrong: since EF Core 3.0 that throws; only the final Select runs client code. Instead: rewrite the predicate or map a SQL function.o.Name.ToLower() == x, o.PlacedAt.Year == y). Why it is wrong: it translates, but the result is non-sargable and scans the index. Instead: compare against ranges or rely on a case-insensitive collation.Expression.Constant for user values. Why it is wrong: every value is a new shape, causing query-cache misses and plan cache bloat. Instead: capture values in closures so they become parameters.o.Customer.Address.City into a non-nullable DTO property). Why it is wrong: SQL returns NULL through the LEFT JOIN, and materialising it into a non-nullable value type throws at runtime. Instead: make the DTO property nullable or use o.Customer != null ? ... : null so the null is explicit.EnableSensitiveDataLogging in production to see parameters. Why it is wrong: it writes personal data to logs, a Privacy Act 1988 risk. Instead: use it only locally; rely on TagWith and Query Store in production.IS NULL branches for nullable comparisons, which changes plans. Instead: make columns non-nullable where the domain allows.ToQueryString() output into the PR for non-trivial queries.LINQ in EF Core is a leaky abstraction by design: it looks like C#, but it is a SQL generator with a subset of C# as input. The senior habit is to think in SQL first and write the LINQ that produces it, then confirm with ToQueryString(). I also care about the two caches: EF Core's compiled-query cache and SQL Server's plan cache. Anything that changes query shape per call (constants in expressions, varying list sizes) hurts both.
On cost: translation is paid once per shape, so for a hot query the steady-state overhead of LINQ over raw SQL is the cache lookup plus materialisation, usually tens of microseconds. Where LINQ really loses is the SQL it can't express well: window functions over large sets, recursive CTEs, query hints, or a correlated subquery EF Core generates where a hand-written join would be cheaper. In those cases I would rather drop to FromSql (still composable and parameterised) or a view than write unreadable LINQ, and I measure with the execution plan and Query Store, not by feel.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Plain LINQ | Most CRUD and reporting queries | Must know the translatable subset | Window functions or hints EF can't express |
HasDbFunction / computed column |
Reused derived logic | Schema or function to maintain | One-off logic |
FromSql composed with LINQ |
Complex SQL, CTEs, hints | SQL lives in C#; less type safety | Simple filters LINQ handles |
| Final-projection client code | Formatting after filtering | Runs per row in the shaper | Large result sets, or logic that filters |
In EF Core, DbSet<T> is an IQueryable<T>, so Where, Select and so on build an expression tree, and EF Core translates it to SQL when you enumerate, caching the translation by query shape. Only what EF understands translates, like properties, operators and many string, date and EF.Functions methods. Since EF Core 3.0, client evaluation is allowed only in the final Select, so anything else untranslatable throws. For reads I use AsNoTracking or projections, AsSplitQuery when collection includes explode, and I check the SQL with ToQueryString(), logging and Query Store.
Because the generated SQL applies the function to every row (LOWER([c].[Email]) = @email, DATEPART(year, [o].[PlacedAt]) = 2026), so SQL Server can't seek an index on the raw column. It scans the whole index instead, which costs CPU and reads proportional to the table and gets worse as data grows. Fixes: express dates as a half-open range (WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end); rely on the database's case-insensitive collation instead of ToLower(), so no function is needed at all; or index a persisted computed column when you really need the derived value.
Last updated 23 Nov 2026.