Entity Framework Core Interview Question #135

What are compiled queries and when should you use them?

Performance, Raw SQL, Stored Procedures & Advanced Queries Senior Advanced

Quick Interview Answer

Compiled queries explicitly precompile an EF Core query delegate so repeated executions can avoid some query-processing overhead. They are most useful for very hot, stable query shapes where profiling shows compilation overhead matters. They add complexity, so first address inefficient SQL, missing indexes, excessive retrieval, and unnecessary round trips.

Detailed Explanation

Compiled queries explicitly precompile an EF Core query delegate so repeated executions can avoid some query-processing overhead. They are most useful for very hot, stable query shapes where profiling shows compilation overhead matters. They add complexity, so first address inefficient SQL, missing indexes, excessive retrieval, and unnecessary round trips.

Code Example

private static readonly Func<AppDbContext, int, Product?> GetProduct =
    EF.CompileQuery((AppDbContext db, int id) =>
        db.Products.FirstOrDefault(p => p.Id == id));