EF Core compiled query cache returns stale results when query captures context property
0 reputation · 09 Jun 2026, 17:07 UTC
Goal
Determine the recommended approach for preventing stale query results when a compiled query in EF Core 7+ captures a mutable property from the DbContext instance.
Constraints and uncertainty
The application uses a long‑running host with a shared compiled query cache across many short‑lived DbContext instances. Each context sets a runtime filter value on a property (e.g., CurrentTenantId) that a compiled query references. Because the compiled delegate is cached by expression signature, the first context’s filter value is baked into the delegate and reused for subsequent contexts, returning data scoped to the wrong tenant.
Documentation notes this as a known limitation and suggests avoiding context capture or manually clearing the cache, but does not prescribe a pattern for multi‑tenant scenarios where the filter must vary per request. Clearing the global ICompiledQueryCache on every request defeats the performance benefit of compilation.
Questions
- What is the supported pattern for parameterizing a compiled query so that per‑context values flow through without capturing the context instance?
- Can the compiled query cache be scoped or partitioned per DbContext instance without disabling compilation entirely?
- Does EF Core 8 or 9 introduce any built‑in mechanism (e.g., cache key customization) that resolves this closure‑capture issue?