Module 1 · Foundations · Lesson 1 of 21
How EF Core Runs a Query: Expression Trees, SQL, Logging and ToQueryString
EF Core runs a query when you consume its results. Use ToQueryString to inspect generated SQL and command logging to see what actually executes.
The important distinction is between holding a query and holding its results. A query describes work that EF Core can perform later. A list contains results from work already performed.
How do DbContext, DbSet and expression trees fit together?
A DbContext is a short-lived database session that coordinates queries, tracked entities and saved changes. It is not the same thing as a permanently open database connection. A DbSet<TEntity> is a starting point for querying one entity type through that context.
An entity is an object EF Core maps to database data, usually a row. The change tracker is the context's record of entity instances and their changes. Normal queries returning entities use tracking by default.
When you build an EF Core query, IQueryable<T> preserves its operations as an expression tree. This is data describing expressions and method calls, rather than instructions that have already read database rows.
Here is a small example you can run without EF Core. It shows the distinction between an expression description and a callable function:
using System; using System.Linq.Expressions; Expression<Func<int, bool>> filter = price => price >= 20; Console.WriteLine(filter.Body); var testPrice = filter.Compile(); Console.WriteLine(testPrice(25));
(price >= 20) True
The first line of output describes the comparison. Compile() turns this particular expression into a function, and calling it with 25 returns True.
EF Core does not run your filter by calling Compile(). Its database provider, the component that connects EF Core to one database system, translates supported operations into that database's SQL.
The mistake to avoid. An IQueryable<Product> is not a collection of products already loaded from the database. It describes how to obtain products.
In an interview, say: “A DbContext represents a database session, and a DbSet is a query starting point for an entity type. IQueryable preserves an expression tree that EF Core and its provider can translate into SQL.”
When does an EF Core query hit the database?
Deferred execution means that constructing a query and running it happen at different times. Where and OrderBy build the query description without executing SQL. Construction still uses processor time and allocates objects.
Enumeration means consuming the sequence, such as through foreach. It executes an EF query. Microsoft's How Queries Work lists other calls that trigger execution.
The following experiment uses EF Core SQLite 10.0.12. SQLite is a real database engine running inside this process. Keeping its in-memory connection open keeps this example's database alive.
Before reading the output, predict:
- How many commands have executed after construction and after
ToQueryString? - Which products does the first
ToListreturn afterminimumchanges? - Does
query.Count()count the existing list or execute another command? - Does running the same query again reuse the previous rows?
The query tags are explained in the TagWith section below.
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
bool measuring = false;
int commandCount = 0;
var commandLogs = new List<string>();
var options = new DbContextOptionsBuilder<ShopContext>()
.UseSqlite(connection)
.LogTo(message =>
{
if (!measuring) return;
commandCount++;
commandLogs.Add(message);
}, new[] { RelationalEventId.CommandExecuted })
.Options;
using var db = new ShopContext(options);
db.Database.EnsureCreated();
db.Products.AddRange(
new Product { Name = "Pen", Price = 10 },
new Product { Name = "Book", Price = 25 },
new Product { Name = "Bag", Price = 40 });
db.SaveChanges();
db.ChangeTracker.Clear();
measuring = true;
int minimum = 20;
var query = db.Products
.TagWith("Catalog.PriceFilter")
.TagWithCallSite()
.Where(p => p.Price >= minimum)
.OrderBy(p => p.Price);
Console.WriteLine($"After construction: commands={commandCount}");
Console.WriteLine(query.ToQueryString());
Console.WriteLine($"After inspection: commands={commandCount}");
minimum = 30;
var rows = query.ToList();
Console.WriteLine($"First list: {string.Join(", ", rows.Select(p => p.Name))}; commands={commandCount}");
int databaseCount = query.Count();
Console.WriteLine($"Query count: {databaseCount}; commands={commandCount}");
minimum = 20;
var again = query.ToList();
Console.WriteLine($"Second list: {string.Join(", ", again.Select(p => p.Name))}; commands={commandCount}");
Console.WriteLine($"Original list count: {rows.Count}; commands={commandCount}");
Console.WriteLine("Executed-command logs:");
foreach (var message in commandLogs)
{
Console.WriteLine(message);
}
public sealed class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int Price { get; set; }
}
public sealed class ShopContext : DbContext
{
public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }
public DbSet<Product> Products => Set<Product>();
}After construction: commands=0
.param set @minimum 20
-- Catalog.PriceFilter
-- File: Program.cs:35
SELECT "p"."Id", "p"."Name", "p"."Price"
FROM "Products" AS "p"
WHERE "p"."Price" >= @minimum
ORDER BY "p"."Price"
After inspection: commands=0
First list: Bag; commands=1
Query count: 1; commands=2
Second list: Book, Bag; commands=3
Original list count: 1; commands=3
Executed-command logs:
info: 12/01/2026 10:47:34.818 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@minimum='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
-- Catalog.PriceFilter
-- File: Program.cs:35
SELECT "p"."Id", "p"."Name", "p"."Price"
FROM "Products" AS "p"
WHERE "p"."Price" >= @minimum
ORDER BY "p"."Price"
info: 12/01/2026 10:47:34.842 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@minimum='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
-- Catalog.PriceFilter
-- File: Program.cs:35
SELECT COUNT(*)
FROM "Products" AS "p"
WHERE "p"."Price" >= @minimum
info: 12/01/2026 10:47:34.843 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@minimum='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
-- Catalog.PriceFilter
-- File: Program.cs:35
SELECT "p"."Id", "p"."Name", "p"."Price"
FROM "Products" AS "p"
WHERE "p"."Price" >= @minimum
ORDER BY "p"."Price"Needs the packages Microsoft.Data.Sqlite 10.0.12 and Microsoft.EntityFrameworkCore.Sqlite 10.0.12. Built and run with them: the output above is what the program really printed.
Timestamps, durations and the source-file location will differ between runs; the command counts and product results are the useful checks. Setup commands are not counted: measuring becomes true only after the database is created and seeded.
The filter reads the captured minimum value when EF processes each execution. The SQL inspection happened with 20, but the first execution uses 30.
query.Count() is still an EF query. It asks the database to count matching rows. In contrast, rows.Count reads the count of an existing list.
Reusing query reuses a description of work. Reusing rows reuses the results already stored in memory. The list does not automatically refresh when you change minimum or database data.
These are database command counts, not network trips, and the SQL is SQLite's: SQL Server and PostgreSQL write it differently.
The mistake to avoid. Keeping a query in a variable does not cache its rows. Repeated execution normally sends SQL again, even through the same context.
In an interview, say: “EF Core uses deferred execution. Where and OrderBy build the query; enumeration or operators such as ToList, First, Count and Any execute it. Building a query still has a CPU and allocation cost. Reusing the query normally executes SQL again; reusing a list that ToList already filled with results does not.”
What changes after AsEnumerable or ToList?
After AsEnumerable(), later operators run in .NET as rows arrive, but the query still runs only when consumed; put filters before it. ToList() runs the query and stores every row. See query translation and client evaluation.
In an interview, say: “For an EF Core query, IQueryable holds an expression tree that the provider translates into SQL for the database. After AsEnumerable, IEnumerable operators run in .NET as rows are read. AsEnumerable alone does not execute the query. ToList executes and stores the results. Moving filters into .NET can fetch unnecessary rows.”
What happens between a LINQ query and its results?
At a high level, EF Core processes the expression tree, identifies values that can become SQL parameters, and checks its query cache. A SQL parameter carries a value separately from the SQL command text.
Parameter extraction is the step that obtains suitable values, such as the captured minimum, for a particular execution. The query cache stores reusable query-processing work, not database result rows.
If EF cannot reuse the necessary cached work, EF and the provider prepare the query, including translating supported operations into database-specific SQL.
flowchart TD
A["LINQ expression tree"] -->|"is processed for"| B["Parameters and cache lookup"]
B -->|"hit: reuses"| C["Provider-specific query"]
B -->|"miss: translates"| C
C -->|"runs as"| D["Database command"]
D -->|"returns values for"| E["Result materialization"]
Materialization means turning returned database values into .NET results, including entity objects when requested.
For a tracking entity query, EF checks whether the context already tracks an entity with the returned key. If so, it can return that existing instance. Otherwise, it creates and tracks an instance. This reuse does not mean the query skipped the database.
That explains a subtle point in the price experiment: running query.ToList() again executes SQL, even though the tracker can reuse the Bag instance already loaded.
The mistake to avoid. The query cache saves EF from translating the same query again. Tracked-instance reuse saves creating a new object for a row EF already tracks. Neither one saves the trip to the database when you execute an ordinary entity query.
In an interview, say: “EF processes the expression tree, extracts suitable values as parameters and checks its query cache. When needed, the provider translates it into SQL. EF executes the command and materializes results. Entity queries track by default and can reuse tracked instances, but the query cache does not cache rows.”
How do ToQueryString and command logging show SQL?
ToQueryString() produces provider-specific SQL for debugging without executing the query. Producing that text can still require query translation, so it is not a zero-work operation.
It is not guaranteed to produce text you can execute directly, and it describes only the query you inspected. In the experiment it shows the ordered entity query, but the later Count() sent SELECT COUNT(*). A terminal operation, such as ToList, First or Count, runs the query and can change its SQL, so an inspected query does not prove what ran.
Use command logs for that evidence. The experiment filters LogTo to RelationalEventId.CommandExecuted, stores each matching message, and prints the messages at the end.
For application logging, the category Microsoft.EntityFrameworkCore.Database.Command selects database-command messages through the normal logging configuration. EF's simple logging documentation explains filtering by event or category. Production applications commonly use EF's integration with Microsoft.Extensions.Logging.
Why is sensitive-data logging risky?
Ordinary command logs mask parameter values. Before using EnableSensitiveDataLogging(), read the Sensitive data guidance. Keep this setting disabled in production and handle development logs carefully.
Leaving it disabled is not a complete SQL-redaction mechanism. A literal written directly into generated SQL remains part of the command text. Since EF Core 10, values that EF inlines for you (for example with EF.Constant) are logged as ?; a literal you write in the lambda still appears. Treat ToQueryString output carefully too; it is not a sanitized production logging interface.
The mistake to avoid. An inspected query string is not a record of execution, and masked parameters do not make every part of a SQL log safe to publish.
In an interview, say: “Use ToQueryString during development to inspect SQL without execution. Use LogTo or the Database.Command category to see commands that actually ran. Tags help connect those commands to application code and database tools. I keep sensitive-data logging disabled in production.”
When should you use Find, FirstOrDefault or SingleOrDefault?
Use Find when you know the primary key, the database key that uniquely identifies an entity row. It first checks tracked instances and queries the database only when necessary.
Use FirstOrDefault when you want one matching row. It executes a query and does not reject multiple matches. Use an explicit ordering when which matching row comes first matters.
Use SingleOrDefault when the query must have at most one match. It executes a query and throws if more than one matches. This check can require reading an additional matching row compared with taking the first.
For entity results, all three return null when nothing is found. First and Single, without OrDefault, throw InvalidOperationException when no row matches. Single also throws when more than one row matches. More generally, the OrDefault methods return the result type's default value when no match exists. See the SingleOrDefault reference.
This independent SQLite example makes the tracker difference visible:
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
int commands = 0;
var options = new DbContextOptionsBuilder<LookupContext>()
.UseSqlite(connection)
.LogTo(_ => commands++, new[] { RelationalEventId.CommandExecuted })
.Options;
using var db = new LookupContext(options);
db.Database.EnsureCreated();
db.Products.AddRange(
new LookupProduct { Id = 1, Name = "Book", Price = 25 },
new LookupProduct { Id = 2, Name = "Bag", Price = 40 });
db.SaveChanges();
db.ChangeTracker.Clear();
commands = 0;
Console.WriteLine($"Default tracking: {db.ChangeTracker.QueryTrackingBehavior}");
var firstFind = db.Products.Find(1);
Console.WriteLine($"First Find: {firstFind?.Name}; commands={commands}");
var secondFind = db.Products.Find(1);
Console.WriteLine($"Second Find: same={ReferenceEquals(firstFind, secondFind)}; commands={commands}");
var firstMatch = db.Products.FirstOrDefault(p => p.Id == 1);
Console.WriteLine($"FirstOrDefault: same={ReferenceEquals(firstFind, firstMatch)}; commands={commands}");
try
{
_ = db.Products.SingleOrDefault(p => p.Price >= 20);
}
catch (InvalidOperationException)
{
Console.WriteLine($"SingleOrDefault: multiple matches; commands={commands}");
}
var missing = db.Products.FirstOrDefault(p => p.Id == 99);
Console.WriteLine($"Missing is null: {missing is null}; commands={commands}");
public sealed class LookupProduct
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int Price { get; set; }
}
public sealed class LookupContext : DbContext
{
public LookupContext(DbContextOptions<LookupContext> options) : base(options) { }
public DbSet<LookupProduct> Products => Set<LookupProduct>();
}Default tracking: TrackAll First Find: Book; commands=1 Second Find: same=True; commands=1 FirstOrDefault: same=True; commands=2 SingleOrDefault: multiple matches; commands=3 Missing is null: True; commands=4
Needs the packages Microsoft.Data.Sqlite 10.0.12 and Microsoft.EntityFrameworkCore.Sqlite 10.0.12. Built and run with them: the output above is what the program really printed.
FirstOrDefault runs SQL even when it returns the tracked object; only Find checks the tracker first.
Microsoft documents the tracker-first behavior under Find and FindAsync. Continue with change tracking and the identity map for how EF keeps one tracked instance per entity key.
The mistake to avoid. FirstOrDefault does not become a tracker-only lookup just because its predicate compares a primary key. That shortcut belongs to Find.
In an interview, say: “Find checks the tracker for a primary key before querying. First and FirstOrDefault take one match. Single and SingleOrDefault reject multiple matches. First and Single throw when nothing matches; the OrDefault versions return default, which is null for entity results. I use Single when multiple matches should be an error.”
How do TagWith and TagWithCallSite identify a query?
A query tag is a comment EF adds to generated SQL so you can recognize the query in application logs and database-side tools.
In the price experiment, TagWith adds the stable label Catalog.PriceFilter and TagWithCallSite adds the source file and line of its call. Both appear as SQL comments in the inspected query and in every executed command.
Use labels describing the operation, not the current user or request. Tags are SQL literals, not SQL parameters. A customer email or access token placed in a tag can appear in logs even when sensitive-data logging is disabled. Source paths from call-site tags can reveal internal project information too.
The official query tags documentation also shows how multiple tags accumulate on one query.
The mistake to avoid. A query tag is not a protected place for request data. Keep it stable and non-sensitive because it becomes part of the SQL text.
In an interview, say: “TagWith adds a recognizable SQL comment for correlating application queries with command logs and database tools. I use stable, non-sensitive labels because tags are literals, not parameters. TagWithCallSite adds the source-file location.”
Check yourself
An EF query is stored in query. You call query.ToQueryString(), query.ToList(), query.Count(), and then read the returned list's Count property. For the simple SQLite query in this lesson, how many database commands execute, excluding setup?
Show answer
Correct answer: A
ToQueryString inspects without execution. ToList executes one command, and query.Count() executes another. Reading the existing list's Count property does not query the database.
What happens with query.AsEnumerable().Where(LocalCheck) before the sequence is enumerated?
Show answer
Correct answer: D
AsEnumerable changes how subsequent LINQ operators run. It does not execute or buffer the underlying query. Enumeration later executes the EF portion and applies LocalCheck in .NET.
Going deeper
One query is not always one command. The experiment deliberately uses simple queries. Loading related collections with split queries can execute multiple commands. Retries can also add execution attempts. Use the actual logs rather than generalizing this experiment's counts; split queries versus single queries explains that choice.
A context is not safe for parallel operations. Await each asynchronous operation before using the same context again, or use separate contexts for parallel work. Dispose contexts you create yourself. Microsoft's DbContext lifetime and configuration guidance explains these restrictions.
Sources
- How Queries Work - EF Core | Microsoft Learn: Deferred execution, the high-level query lifecycle, materialization and tracked-instance reuse.
- Simple logging - EF Core | Microsoft Learn: LogTo configuration, event filtering, command categories, production logging integration and sensitive-data logging.
- Query Tags - EF Core | Microsoft Learn: TagWith SQL comments, cumulative tags, TagWithCallSite source locations and non-parameterizable tag literals.
- EntityFrameworkQueryableExtensions.ToQueryString Method: SQL inspection for debugging without query execution and the warning that the returned text is not necessarily directly executable.
- Accessing Tracked Entities - EF Core | Microsoft Learn: Primary-key Find behavior, tracker-first lookup and avoiding a second query for an already tracked entity.
- DbContext Lifetime, Configuration, and Initialization - EF Core | Microsoft Learn: Context lifetime, configuration, disposal and the prohibition on parallel operations on one context.
- What's New in EF Core 10 | Microsoft Learn: EF Core 10 redacts the values it inlines (EF.Constant) from logged SQL.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·