What is a compiled query in EF Core?
Quick Answer
Every LINQ query EF Core runs must be parsed and translated to SQL. EF caches that translation, but the cache lookup itself has a cost. A compiled query (EF.CompileAsyncQuery(...)) does the translation once, up front, and gives you a delegate that skips even the cache lookup — worth it only for queries run extremely frequently in a hot path.
When EF Core runs a LINQ query it has to translate it to SQL. It caches that translation so it doesn't re-translate the same query shape, but even the cache lookup has a small cost. A compiled query moves that work to startup: you call EF.CompileAsyncQuery once, store the delegate, and calling it skips the lookup entirely. The gain is a few percent, so it's only worth it for a query that runs thousands of times a second. Honestly EF Core does automatic query compilation internally now, so I rarely reach for it.
private static readonly Func<AppDbContext, int, Task<Customer?>> _byId = EF.CompileAsyncQuery((AppDbContext db, int id) => db.Customers.FirstOrDefault(c => c.Id == id));- Call it:
await _byId(db, id). - Gains are modest (a few % on query-bound throughput) — measure before adopting; most apps don't need it.
- EF Core has automatically compiled queries internally since 6.0, so the manual gain shrank.