In EF Core, how do you see the SQL a LINQ query will send without running it, and where does ToQueryString fall short?
answer
- extension method on IQueryable
- returns a string, executes nothing
- parameters shown as comment lines
- no Count or First: they are not IQueryable
- split query shows the first statement only
basics
~20 sCall 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.
solid answer
~40 s`ToQueryString()` is an extension method on `IQueryable` from `EntityFrameworkQueryableExtensions`. It compiles the query and returns the command text without running it; on a relational provider such as Npgsql each parameter is printed as a comment line, like `-- @projectId='42'`, above the SQL. It is meant for debugging and tests, not for execution. Its limits: it only works on something that is still an `IQueryable`, so `CountAsync`, `FirstOrDefaultAsync`, `AnyAsync` or `ExecuteDeleteAsync` cannot be inspected this way because they execute immediately; for a split query it shows only the first SQL statement and appends a note that more queries may follow; and on a non-EF `IQueryable` it returns a fixed message instead of SQL. For everything it cannot show, I read the commands EF logs at run time.
code
csharp · 10 lines[Fact]
public void Overdue_query_translates()
{
using var db = CreateContext();
var sql = db.WorkItems
.Where(w => w.DueDate < DateOnly.FromDateTime(DateTime.UtcNow))
.ToQueryString();
Assert.Contains("WHERE", sql);
}go deeper
Know that ToQueryString() on an IQueryable shows the SQL EF Core will send, and that it does not run the query.
Explain what the output contains, why terminal operators like CountAsync cannot be inspected with it, and how split queries are reported.
Use ToQueryString in tests to prove queries translate, and switch to the executed-command log when diagnosing slow pages with several statements.
Decide where query visibility lives in the team's workflow: translation tests in CI versus run-time command logging in shared environments.
## What ToQueryString does `ToQueryString()` is defined on `IQueryable` in `EntityFrameworkQueryableExtensions`. It takes the expression tree, runs it through the same query pipeline EF Core uses for execution, and returns the SQL text that would be sent — **without opening a connection or reading any rows**. The documentation describes the output as intended for debugging; it "may not be suitable for direct execution". On the project-tracking dashboard: ```csharp var query = db.WorkItems .Where(w => w.ProjectId == projectId && !w.IsDone) .OrderBy(w => w.DueDate) .Select(w => new { w.Id, w.Title, w.DueDate }); Console.WriteLine(query.ToQueryString()); ``` With the Npgsql provider the output looks like this: ```sql -- @projectId='42' SELECT w."Id", w."Title", w."DueDate" FROM "WorkItems" AS w WHERE w."ProjectId" = @projectId AND NOT (w."IsDone") ORDER BY w."DueDate" ``` Two details are worth knowing: - The relational provider writes **each parameter as a comment line** (`-- @name='value'`) above the command text, including the value. That makes the output useful for pasting into a SQL console after replacing the parameters. - In EF Core 10 parameter names are **simplified**: a captured local `projectId` becomes `@projectId`, where EF Core 8 and 9 produced names like `@__projectId_0`. Because it compiles the query, `ToQueryString()` also surfaces translation failures: an untranslatable `Where` throws the same `InvalidOperationException` here as it would at `ToListAsync()`. That makes it handy in a unit test that asserts a query translates. ## Where it falls short | Situation | What you get | |---|---| | Ordinary `IQueryable` | The SQL plus parameter comment lines | | Query ending in `CountAsync`, `FirstOrDefaultAsync`, `AnyAsync`, `SumAsync` | Nothing to call it on: these execute and return a value, not an `IQueryable` | | `ExecuteUpdateAsync` / `ExecuteDeleteAsync` | Same: they execute immediately | | Query with `AsSplitQuery()` | Only the **first** statement, followed by a note that additional queries may run depending on the first one's results | | An `IQueryable` that EF did not create (for example `list.AsQueryable()`) | The string *"The given 'IQueryable' does not support generation of query strings."* | For the terminal-operator case you can inspect the query **before** the operator — `query.ToQueryString()` shows the `SELECT` that `CountAsync` would wrap in `COUNT(*)` — but the final SQL differs. ## Reading the output critically The string is a debugging aid, so read it with a few caveats in mind: - The parameter lines are **comments**, not declarations. To run the statement in a SQL console you replace each `@name` with its value or declare it yourself. - Values are formatted for humans: strings and numbers in quotes, `NULL` for nulls, and only the **first five elements** of an array parameter followed by `...`. - Values that EF **inlines** as constants, for example through `EF.Constant(...)`, appear inside the SQL text itself rather than as parameter lines. - The SQL is what EF generates for **this provider and this model**; the same LINQ against SQL Server or SQLite produces different text, so check it with the provider you deploy. A useful habit is to put `ToQueryString()` behind a breakpoint or a debugger watch while writing a new query, then delete it; it costs a full query compilation, so it does not belong on a hot path in production code. ## Seeing everything at run time When you need every statement, including split-query follow-ups, aggregates and bulk updates, read the commands EF Core logs as it executes them. The `Microsoft.EntityFrameworkCore.Database.Command` log category records each command; configuring logging and showing parameter values is a separate tuning topic. A practical workflow: 1. During development, call `ToQueryString()` in a debugger watch or a test to check the shape of a query. 2. When a page is slow, read the executed-command log to count statements and see the real parameters. 3. Take the SQL to the database's own `EXPLAIN` tooling to read the plan. ## Why interviewers ask The question checks whether a candidate verifies what EF sends instead of guessing. A good answer names the method, says it does not execute, and knows the blind spots: terminal operators, split queries and non-EF queryables.
- Why can't you call ToQueryString on db.WorkItems.CountAsync()?`CountAsync()` executes the query and returns `Task<int>`; there is no `IQueryable` left to call `ToQueryString` on. You can call it on the query before `CountAsync` to see the inner `SELECT`, or read the executed-command log to see the actual `COUNT(*)` statement.
- Does ToQueryString need a reachable database?No. It builds the command text through the provider without opening a connection or executing anything, so it works in a test with a context configured for the provider but no running server. It still needs a relational provider; on a non-EF queryable it returns a fixed message.
- ToQueryString runs the query and returns the results as text.
- ToQueryString shows every statement a split query sends.
- You can call ToQueryString after FirstOrDefaultAsync.
- The SQL is only visible with a database profiler.
Assumes EF Core 10, whose simplified parameter names (@projectId rather than EF Core 8 and 9's @__projectId_0) appear in the ToQueryString output.