Covers where EF Core spends time outside SQL (query compilation and cache lookup, model building at start-up), compiled queries with EF.CompileAsyncQuery, compiled models with dotnet ef dbcontext optimize and MSBuild integration, precompiled queries and the experimental Native AOT support in EF Core 10.
They target two different overheads outside the SQL. Compiled queries (EF.CompileAsyncQuery) remove the per-execution work of looking up a LINQ query in EF Core's query cache (hashing and comparing the expression tree). EF Core already caches translations, so the gain is microseconds per call, worth it only for very hot queries. Compiled models (dotnet ef dbcontext optimize) remove start-up work: building the model by convention and reflection on first use, which can take seconds for hundreds of entity types. They must be regenerated when the model changes (EF Core 9+ can do it on build). Precompiled queries and Native AOT go further but are still experimental in EF Core 10. The trade-off: real gains in narrow cases, extra build steps and limitations everywhere else, so I measure first.
"When an EF Core query runs, there's work before the SQL: EF Core takes the LINQ expression tree, computes a cache key, and looks it up in its compiled query cache. The first time, it translates the query to SQL and builds a materialiser delegate; after that it reuses them, but the lookup still walks and compares the expression tree on every call. Separately, the first use of a context type builds the model: it scans entity types, applies conventions and your configuration. For a typical model that's tens of milliseconds; for a model with several hundred entities it can be several seconds of cold start.
Compiled queries attack the first cost.
EF.CompileAsyncQueryturns the LINQ into a delegate once, so calls skip the cache lookup. Because EF Core already caches, the gain is small, a few microseconds per execution, and it only shows on queries running thousands of times a second where the SQL itself is trivial, like a key lookup. Compiled models attack the second cost.dotnet ef dbcontext optimizegenerates C# that constructs the model directly, and you load it withUseModel. The catch is that it's generated code: if someone changes the model and doesn't regenerate, it's out of date. EF Core 9 added MSBuild integration so it can regenerate on build, and some features have limitations with compiled models, so I check the docs list for the version in use.For example, at [company] we had [a function app / container] with [about 600 entity types] where the first request after a scale-out took [around 8 seconds]. I [generated a compiled model and wired regeneration into the build], and the first request dropped to [about 1.5 seconds]. Beyond that, EF Core 9 introduced precompiled queries and Native AOT support, and as of EF Core 10 they're still marked experimental, so I wouldn't ship them to production yet. The mistake I see is reaching for compiled queries when the time is in SQL. I profile first."
| Feature | Removes | Typical gain | Cost |
|---|---|---|---|
| Query cache (built in) | Re-translating LINQ each time | Large, automatic | Cache lookup per call |
EF.CompileQuery / CompileAsyncQuery |
The cache lookup | Microseconds per call | Separate static delegate per query; no composition after compile |
Compiled model (dbcontext optimize) |
Model building at first use | Seconds for very large models | Generated code to regenerate; feature limitations |
Precompiled queries (--precompile-queries) |
Runtime translation entirely | Start-up and AOT enablement | Experimental; limitations on dynamic queries |
| Native AOT | JIT and reflection | Start-up, memory | Experimental for EF Core 10; many restrictions |
A serverless API [in a system I worked on] with about 600 entity types had cold starts of around 8 seconds, mostly model building, visible in a start-up trace. A compiled model brought the first request to about 1.5 seconds. Compiled queries on the hottest lookup, by contrast, saved about 4 microseconds per call: measurable in BenchmarkDotNet, invisible in production p95, so we kept only the compiled model.
Checks that the candidate understands where EF Core spends time outside SQL, can distinguish compiled queries from compiled models, knows the current status of precompiled queries and Native AOT, and measures before optimising.
Green flags
Expression.Constant cache-miss problemRed flags
LINQ expression tree
│ (every execution)
├─ parameter extraction: closure values become parameters
├─ cache lookup: hash + structural comparison of the tree
│
├─ cache miss (first time): translate -> SQL + materialiser delegate -> store
└─ cache hit: reuse SQL and delegate
│
└─ execute command, materialise rows
Parameter extraction and the cache lookup are the per-call overhead compiled queries remove; translation already happens only once. If you inline constants that change (for example by building expressions with Expression.Constant for user input), every variation is a cache miss and a new translation: that's the real performance bug to look for. It shows up as high CPU and a falling query cache hit rate in the EF Core event counters (dotnet-counters monitor Microsoft.EntityFrameworkCore).
EF.CompileAsyncQuery((AppDbContext db, int id) => db.Orders.Single(o => o.Id == id)) returns a delegate that takes the context and parameters. EF Core translates it once; calls go straight to execution. Limits: you cannot compose more LINQ on the result, parameters must be passed as arguments, and each shape needs its own delegate. Gains are in the low microseconds per call, so they matter only at thousands of executions per second on queries whose SQL takes well under a millisecond.
The model is built once per context type per process and then cached; every context instance reuses it. The cost is paid at first use: EF Core runs conventions over every entity type, reads attributes and your OnModelCreating, and builds the runtime model. That cost grows with entity and property count. A compiled model doesn't change how the model is used at run time; it changes how it is built. dotnet ef dbcontext optimize --output-dir CompiledModels --namespace Shop.Data.CompiledModels generates classes that construct the runtime model directly, and the context uses options.UseModel(AppDbContextModel.Instance). EF Core 9+ can generate it during build with the Microsoft.EntityFrameworkCore.Tasks package and <EFOptimizeContext>true</EFOptimizeContext>, which removes the stale-model risk. Some features have historically had limitations with compiled models; check the current list for your EF Core version.
EF Core 9 added experimental support for precompiling LINQ queries at publish time using C# interceptors, which also enables Native AOT. As of EF Core 10 (November 2026), Microsoft still marks Native AOT and query precompilation as experimental and not recommended for production. Known limitations: only queries the analyser can see statically are precompiled, so dynamically composed queries (built conditionally across methods, or from expression builders) are not supported; value converters that use captured state are not supported; and the database provider must implement support. Third-party reports have described build-time memory problems with PublishAot plus EFOptimizeContext in some 10.0.x patch versions, so pin and test patch versions if you experiment.
dotnet-trace collect around the first request, or simple timing around the first query; Application Insights request duration for the first request after a restart.EF.CompileAsyncQuery; note the difference in microseconds and allocations.<EFOptimizeContext>true</EFOptimizeContext> and confirm the compiled model regenerates on build after a model change.Expression.Constant for user input in a loop and watch the query cache hit rate fall in dotnet-counters.A compiled query for a hot lookup, and a compiled model wired into DI.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public sealed record ProductPrice(int Id, decimal Price);
public static class HotQueries
{
// Translated once; each call skips the expression-tree cache lookup.
public static readonly Func<AppDbContext, int, CancellationToken, Task<ProductPrice?>> PriceById =
EF.CompileAsyncQuery((AppDbContext db, int id, CancellationToken ct) =>
db.Products
.Where(p => p.Id == id)
.Select(p => new ProductPrice(p.Id, p.Price))
.FirstOrDefault());
}
public sealed class PriceService(AppDbContext db)
{
public Task<ProductPrice?> GetAsync(int id, CancellationToken ct) => HotQueries.PriceById(db, id, ct);
}
# Generate a compiled model once (or let MSBuild do it on every build, below).
dotnet ef dbcontext optimize --output-dir CompiledModels --namespace Shop.Data.CompiledModels
<!-- Shop.Data.csproj: regenerate the compiled model on build (EF Core 9+). -->
<PropertyGroup>
<EFOptimizeContext>true</EFOptimizeContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" Version="10.0.*" PrivateAssets="all" />
</ItemGroup>
// Program.cs: load the generated model instead of building it at first use.
builder.Services.AddDbContext<AppDbContext>(o => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
.UseModel(Shop.Data.CompiledModels.AppDbContextModel.Instance));
Expression.Constant for changing values. Why it is wrong: every value is a new cache entry and a new translation, costing CPU and memory. Instead: capture values in closures so EF Core parameterises them.Most EF Core time in production is SQL and network, so these features are for the cases where profiling shows EF Core itself on the critical path: cold starts with very large models (serverless, scale-to-zero containers, frequent scale-outs) and extremely hot, trivial queries. I keep compiled models generated by the build so they cannot go stale, and I treat precompiled queries and Native AOT as watch items until Microsoft drops the experimental label.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Compiled query | Hot key lookups at thousands of calls per second | Static delegates, no composition | Anything dominated by SQL time |
| Compiled model | Large models, cold-start sensitive hosting | Build step, feature limitations | Small models (start-up already fast) |
| ReadyToRun / tiered PGO | General start-up and JIT cost | Larger binaries | When AOT is required anyway |
| Precompiled queries / Native AOT | Experiments, edge deployments | Experimental in EF Core 10, many limits | Production systems today |
For one query, ToQueryString() shows the SQL without running it. For a running app, LogTo(Console.WriteLine, LogLevel.Information) or, in ASP.NET Core, setting the Microsoft.EntityFrameworkCore.Database.Command log category to Information logs each command with its duration. TagWith("Orders list") puts a SQL comment in the statement (and TagWithCallSite() adds file and line), so a slow query found in Query Store or a trace leads straight back to the code. EnableSensitiveDataLogging adds parameter values to logs: useful locally, but it leaks personal data and secrets, so never in production. In production, Application Insights / OpenTelemetry record each SQL command as a dependency with timing, and capturing SQL text is opt-in. The trade-off is visibility versus log volume, cost and privacy.
Start from db.Products.AsNoTracking() as an IQueryable<T> and add Where clauses conditionally; each one ANDs into the same SQL WHERE. For OR logic, combine Expression<Func<T,bool>> predicates by rebinding their parameters (or use LinqKit), never Func<T,bool>, which would force in-memory evaluation.
For sorting, map the client's string to a whitelisted dictionary of key-selector expressions and always add ThenBy(x => x.Id) so paging is stable. Cap the page size on the server. Values captured in closures become SQL parameters, so there's no injection risk and plans are reused.
The trade-off: flexible search is easy to compose, but every optional filter combination is a different SQL shape, so index for the common ones and test the translation.
EF Core's query cache key includes constants in the expression tree, so queries built with Expression.Constant(userValue), string-built dynamic LINQ, or EF.Constant on varying values create a new cache entry and a new translation for every value. The impact: CPU spent translating on every request instead of once, memory growing with cached entries (until the cache's size limit evicts them, causing more re-translation), and on SQL Server a matching flood of single-use plans in the plan cache. Fix it by capturing values in closures (they become SQL parameters), building dynamic predicates with parameter expressions, avoiding EF.Constant for high-cardinality values, and confirming with the query cache hit rate in dotnet-counters monitor Microsoft.EntityFrameworkCore.
How to tell it (STAR)
**S:** Our [API] on Azure Container Apps had [7-9 second] first requests on every new replica, which hurt us during morning scale-outs. **T:** I was asked to bring cold-start latency down without over-provisioning. **A:** A dotnet-trace capture showed the time was EF Core building our [600-entity] model, not SQL. I added a warm-up query to the readiness probe as an immediate fix, then generated a compiled model, had the build regenerate it automatically, and checked in CI that it never goes stale. I also benchmarked compiled queries and found they saved only microseconds, so I left them out. **R:** First-request time dropped to about [1.5 seconds], and the readiness probe means users no longer hit cold replicas at all.
Last updated 23 Nov 2026.