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

📚 Interview question

How does EF Core translate a LINQ query into SQL? What kinds of expressions translate, where is client evaluation still allowed, what happens when something cannot be translated, and how do you check the SQL EF Core will send?

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.

Intermediate Theory Intermediate client-evaluation diagnostics ef-core linq-translation querying sql-server

🎯 Key points

  • Expression tree -> preprocessing -> SQL expression tree -> SQL text, cached by shape
  • Captured variables become SQL parameters; constants are inlined
  • Translation is provider-specific: SQL Server registers its own method translators
  • Translates mapped members, operators and known methods (string, Math, DateTime, EF.Functions)
  • From EF Core 3.0 through EF Core 10, only the final Select may contain client code
  • Untranslatable parts elsewhere throw InvalidOperationException, never silent client eval
  • ToQueryString(), LogTo and TagWith to see and label the SQL
  • EF Core 10: LeftJoin/RightJoin operators; Contains over a collection sent as multiple scalar parameters by default on relational providers

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"When I enumerate an EF Core query, the provider gets the expression tree that the Queryable operators built. EF Core first preprocesses it: it expands navigations into joins, inlines query filters and normalises things like Any and Contains. Then the relational layer translates each node into a SQL expression, using method-call translators the SQL Server provider registers, so string.StartsWith becomes LIKE N'abc%', DateTime.Year becomes DATEPART(year, ...), and EF.Functions.Like maps 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 final Select, because by then the rows are already filtered. Anywhere else, EF Core throws InvalidOperationException: 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 use LogTo or the Microsoft.EntityFrameworkCore.Database.Command log category, with TagWith so I can find the query in Query Store later. If I can't read the SQL, I don't ship the query."


What translates on SQL Server

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

What does not translate

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

Ways to see the SQL

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

Production example

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.

🔍 What the interviewer is checking

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

  • Describes the tree-to-SQL pipeline and query caching.
  • States the final-projection client-evaluation rule from EF Core 3.0.
  • Uses ToQueryString(), LogTo or TagWith without prompting.
  • Mentions parameters versus constants or null semantics.

Red flags

  • Thinks EF Core silently evaluates anything it can't translate.
  • Fixes translation errors with ToList().
  • Has never looked at generated SQL.

📚 Learn in depth

1. The query pipeline

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.

2. Parameters versus constants

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.

3. Null semantics

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.

4. Client evaluation in the final projection

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

5. Translation failures

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

6. Collections and EF Core 10

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

Try it yourself

  1. Call ToQueryString() on five queries: a Contains, a StartsWith, a GroupBy, an Any and a date-part filter. Compare the SQL.
  2. Put a private static method inside Where and read the exception; then move it into the final Select.
  3. Compare Where(o => o.CustomerId == id) with Where(o => o.CustomerId == 42) in the log and look for @__id_0.
  4. Make a nullable column comparison and see the extra IS NULL branch; then make the column required and compare.
  5. Add TagWith("demo"), run the query and find the comment in SQL Server's Query Store or sys.dm_exec_query_stats.

💻 Code

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]

⚠ Common mistakes

  • Mistake: Expecting EF Core to evaluate untranslatable code in a 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.
  • Mistake: Wrapping columns in functions (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.
  • Mistake: Building expression trees with 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.
  • Mistake: Projecting through an optional navigation as if it were always there (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.
  • Mistake: Testing queries against SQLite or the in-memory provider and assuming SQL Server behaves the same. Why it is wrong: translation is provider-specific; a query can translate on one and throw or differ (case sensitivity, date functions) on another. Instead: run query tests against SQL Server, for example with Testcontainers.
  • Mistake: Turning on 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.
  • Mistake: Assuming C# null semantics in raw SQL thinking. Why it is wrong: EF Core adds IS NULL branches for nullable comparisons, which changes plans. Instead: make columns non-nullable where the domain allows.
  • Mistake: Not reading the SQL in code review. Why it is wrong: translation surprises (correlated subqueries, cartesian joins) only show in the SQL. Instead: paste ToQueryString() output into the PR for non-trivial queries.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions compiled queries, split queries or tuning generated SQL. Why: Checks the broader LINQ to Entities picture including tuning.
    How to answer

    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.

  2. When: Candidate shows a translated query with a function on a column. Why: Checks understanding of sargability from the EF Core side.
    How to answer

    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.

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me