LINQ Interview Question #121
What is a compiled query in Entity Framework Core?
LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced
Quick Interview Answer
A compiled query allows EF Core to reuse a precompiled query representation for repeatedly executed query shapes. This can reduce some query-processing overhead in performance-sensitive scenarios.
Detailed Explanation
A compiled query allows EF Core to reuse a precompiled query representation for repeatedly executed query shapes. This can reduce some query-processing overhead in performance-sensitive scenarios.
Compiled queries are an optimization tool, not a default requirement. Database execution time, indexes, result size, and network costs are often more significant and should be measured first.
Code Example
private static readonly Func<AppDbContext, int, Product?>
GetProductById =
EF.CompileQuery(
(AppDbContext db, int id) =>
db.Products.FirstOrDefault(p => p.Id == id));
var product = GetProductById(db, 10);