Search for a command to run...
Every API has one query that runs far more often than the rest. A product lookup by SKU, an order lookup by id, a user lookup by email. It is small, it returns one row, and it sits on the hottest path in the system. When that endpoint feels slow, the instinct is to reach for the database: add an index, rewrite the SQL, check the query plan. All of that matters. But before any of it, there is a cost that lives entirely on the application side, and for a small hot query it can be as large as the database call itself: compiling the LINQ query.
That is what EF Core compiled queries remove. They are not a new feature, not a package, and not a rewrite. They are one static field per hot query, and on the right query they are the closest thing EF Core has to a free performance win.
When you write a LINQ query against a DbSet, EF Core does more than send SQL. It walks the expression tree you built, translates it against the model, produces a SQL query, and builds an execution plan for that query. EF Core does cache that plan, so the second execution of the same query is cheaper than the first. But cheaper is not free: every execution still builds the expression tree, still does the cache lookup, and still binds the parameters into the plan. For a query that returns ten thousand rows, that overhead disappears into the database and network time. For a query that returns one row by primary key, it does not. The translation work can rival the actual database work, and you pay it on every single request.
A compiled query moves that work out of the request path. You compile the query once, EF Core keeps the finished delegate, and each call just invokes it with new parameter values. The database still gets hit on every call. Nothing is cached at the result level. What disappears is the repeated translation.
EF.CompileQuery takes a LINQ expression and returns a delegate. The DbContext is the first argument, because the compiled query is not tied to one context instance, and the rest of the arguments are the query parameters, passed explicitly:
Two details in that definition matter. First, it is static and readonly, defined once per query shape. A compiled query created inside a method on every call buys you nothing; the whole point is that the compilation happens once. Second, the parameters are explicit arguments to the delegate. You do not close over a local variable and hope EF Core notices. You pass the SKU in when you call it, and the same compiled delegate serves every SKU.
The service code barely changes. The DbContext is still scoped per request, as it should be. The compiled delegate just accepts it as an argument, so there is no singleton-context trap and no lifetime change to reason about:
That second example shows the other rule: a compiled query has a fixed shape. The Include is part of the compiled delegate. If some callers want the order with items and others want it without, those are two query shapes, and they need two compiled queries. That is a small price, but it is a price, and it decides where compiled queries belong.
Dynamic queries. If the Where clause, the ordering, or the Includes change based on the request, the expression tree changes, and one compiled delegate cannot cover all of it. A search endpoint with five optional filters is not a compiled-query candidate. Compile the two or three fixed shapes that actually get traffic, and leave the dynamic search as a normal query.
One-off queries. An admin report that runs once a day gains nothing measurable from skipping translation once. The extra indirection costs readability for no return. Compiled queries are for queries that run thousands of times, not for queries that run once.
Fixing a bad query. A compiled query does not fix an N+1, a missing index, or a result set of ten thousand rows pulled into memory. If the database time dominates, the compilation saving is invisible. Fix the query first, then compile the fixed version.
Caching results. This is the misconception to kill early. A compiled query still queries the database on every call. If you want to avoid the database call itself, that is a caching decision, with invalidation to design, and it is a different conversation.
One more distinction, because the names collide: compiled queries are not compiled models. A compiled model, available since EF Core 6, pre-generates the model metadata to speed up application startup. A compiled query pre-generates a query execution plan to speed up repeated execution. They solve different problems, they compose fine, and neither replaces the other.
Do not adopt compiled queries on faith, and do not quote a percentage you read somewhere else. The gain depends entirely on the ratio of translation time to database time for your query, on your data, against your database. Measure it with BenchmarkDotNet, normal query versus compiled query, same database, same data, warmed up, and look at both the mean time and the allocations. A small hot lookup will usually show a clear win in both. A heavy query will show almost nothing, and that null result is useful: it tells you the query was never translation-bound, and your optimisation budget belongs somewhere else.
Run that on the query you actually suspect, not on a toy. If the compiled version is not meaningfully faster for that query, delete the compiled version. The goal is not to have compiled queries. The goal is to have fewer wasted cycles on the path every request takes.
Compile the queries that run thousands of times. Leave the rest readable.
That is the whole discipline. Find the two or three queries your API cannot avoid, the lookups by id and by SKU that every page load and every checkout touches. Give each one a static compiled delegate, keep the DbContext lifetime exactly as it is, and measure the before and after. No schema change, no new dependency, no behaviour change for the caller. The database still does its job on every call; your application just stops paying to re-translate the same question every time it asks it.
A list of orders in memory, rows streaming out of a database, pages from an API - from the consumer's side they are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is that question answered as an interface pair, and in .NET it is the shape of foreach and LINQ themselves: hand-built enumerators, yield return, deferred execution, and the async twin IAsyncEnumerable<T> - including the costs, and when a List is the honest answer.
An order is placed, and five parts of the system need to know. The Observer pattern flips who knows about whom: the publisher announces one fact, subscribers come and go, and the publisher never changes. From hand-built subjects to C# events, IObservable<T>, and MediatR notifications - with the push and pull models demonstrated in code - including the costs, and when a direct call is the honest answer.
A price is not a decimal, a phone number is not a string, and an email is not a string either. Primitive obsession is the habit of modelling domain concepts with the language's built-in types — and value objects are the small, boring, enormously effective fix.