Phase 26 of 30 · Topic 26.4

Compiled Queries (`EF.CompileAsyncQuery`) for Sub-Millisecond APIs

1Concept

EF Core translates LINQ expression trees into SQL queries. `EF.CompileAsyncQuery` compiles and caches the SQL translation once, allowing subsequent invocations to skip LINQ expression parsing entirely.

2Architecture Diagram

Standard LINQ:
Query Invocation ──> Parse Expression Tree ──> Translate to SQL ──> Execute DB Query (1.5ms overhead)

Compiled Query:
Pre-compiled SQL ──> Directly bind parameters and execute (0.2ms overhead!)

3Code Example

C# 13 & .NET 9
using System;

public class CompiledQueryConceptDemo
{
    public static void Main()
    {
        Console.WriteLine("Compiled Query declaration:");
        Console.WriteLine("private static readonly Func<AppDbContext, int, Task<User?>> GetUserById =");
        Console.WriteLine("    EF.CompileAsyncQuery((AppDbContext db, int id) =>");
        Console.WriteLine("        db.Users.AsNoTracking().FirstOrDefault(u => u.Id == id));");
    }
}

4Expected Output

Compiled Query declaration:
private static readonly Func<AppDbContext, int, Task<User?>> GetUserById =
    EF.CompileAsyncQuery((AppDbContext db, int id) =>
        db.Users.AsNoTracking().FirstOrDefault(u => u.Id == id));

5Key Takeaways

  • Use compiled queries on hot microservice endpoints called thousands of times per second.
  • Store compiled queries in `static readonly` fields.
  • Saves CPU cycles spent on LINQ AST tree parsing.