Tutorials Entity Framework Core Tutorial
Compiled Queries in EF Core
Compiled Queries in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 54 of 100
Compiled Queries in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~10 min · Module 6: Advanced EF Core
What is this?
Compiled queries cache the LINQ translation plan so EF skips recompiling the same query shape on every call — defined with EF.CompileAsyncQuery or EF.CompileQuery.
Why should you care?
ShopNest product-by-id lookup runs millions of times daily — compiled query shaves CPU on hot paths.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
private static readonly Func<ShopNestDbContext, int, Task<Product?>> GetProductById =
EF.CompileAsyncQuery((ShopNestDbContext db, int id) =>
db.Products.AsNoTracking().FirstOrDefault(p => p.Id == id));
// Usage:
var product = await GetProductById(_context, productId);
What happened?
- CompileAsyncQuery builds expression once at static initialization.
- Each call reuses compiled delegate — parameters passed separately.
Practice next
- Identify extremely hot queries with stable shape.
- Extract to static readonly compiled delegate.
- Pass DbContext instance per call — still scoped.
- Compile category product list query with categoryId parameter.
- Compare TagWith logged compile time first vs subsequent calls.
Remember
Compiled queries reuse translation plans. Best for fixed-shape hot reads. Pass context as parameter each call.
ShopNest PDP hot path
Product detail microservice uses compiled GetProductById for cache miss database fallback.
Outcome: Microseconds saved per request aggregate to meaningful CPU savings at scale.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!