Repository navigation
Translate captured IQueryable variables to common table expressions - #39803
Aykuttonpc wants to merge 1 commit into
Conversation
When a query references a captured IQueryable variable inside a lambda, translate it to a named common table expression (WITH clause) instead of inlining the subquery at every use site. - The funcletizer wraps the captured query in an EmbeddedQueryable marker carrying the variable name. Non-relational providers translate it as before, since the default TranslateEmbeddedQuery inlines it; the relational override pushes it down into a subquery annotated with the CTE name. - Navigation expansion keeps the embedded query's structure so the outer query can still bind navigations. Shapes that a snapshot can't keep (entities nested in an anonymous type or DTO, subquery or collection projections, groupings, owned types) stay inlined. - QuerySqlGenerator hoists all CTEs to the root statement (SELECT, UPDATE, DELETE), dedupes them, and renames a CTE whose name clashes with a table, table alias, table-valued function or identifier in raw SQL. - SqlTreePruner removes CTE columns that no reference uses. - SQL Server emits SET NOCOUNT OFF before the WITH clause. - SQLite's subquery-to-join rewriter and APPLY flattening leave CTE references alone, since the CTE is referenced by name. - Join pruning doesn't treat a CTE-backed inner as the full table. Fixes dotnet#29918
There was a problem hiding this comment.
🟡 Changes recommended
Generated CTE names can exceed SQL Server’s identifier limit, while deduplicating volatile captured queries can change SQLite results by sharing a sample instead of evaluating references independently.
2 open issues
What changed in this PR
This PR translates eligible captured IQueryable variables into named common table expressions (CTEs), improving generated SQL readability and reuse as requested in #29918.
Changes:
- Adds captured-query markers and translation hooks, retaining inline behavior for unsupported shapes.
- Adds CTE generation, deduplication, name-collision handling, and shared-column pruning.
- Adds relational regression tests and updates SQL Server and SQLite baselines.
| File | Description |
|---|---|
test/EFCore.SqlServer.FunctionalTests/Query/TemporalOwnedQuerySqlServerTest.cs |
Adds temporal owned-navigation baselines. |
test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerTest.cs |
Updates temporal query reuse baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/SqlQuerySqlServerTest.cs |
Updates raw SQL composition baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs |
Adds owned-navigation and fallback baselines. |
test/EFCore.SqlServer.FunctionalTests/Query/NorthwindWhereQuerySqlServerTest.cs |
Updates captured-query predicate baselines. |
test/EFCore.SqlServer.FunctionalTests/Query/NorthwindCommonTableQuerySqlServerTest.cs |
Adds SQL Server CTE baselines. |
test/EFCore.SqlServer.FunctionalTests/Query/Inheritance/TPTGearsOfWarQuerySqlServerTest.cs |
Updates table-per-type query reuse baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/Inheritance/TPCGearsOfWarQuerySqlServerTest.cs |
Updates table-per-concrete-type query reuse baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs |
Updates shared-query parameter baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/FromSqlQuerySqlServerTest.cs |
Updates captured FromSql baseline. |
test/EFCore.SqlServer.FunctionalTests/Query/AdHocMiscellaneousQuerySqlServerTest.cs |
Updates aggregate and nested-query baselines. |
test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqlServerTest.cs |
Adds CTE update/delete baselines. |
test/EFCore.Sqlite.FunctionalTests/Query/NorthwindCommonTableQuerySqliteTest.cs |
Adds SQLite CTE baselines. |
test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs |
Updates shared-query parameter baseline. |
test/EFCore.Sqlite.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqliteTest.cs |
Adds CTE update/delete baselines. |
test/EFCore.Relational.Specification.Tests/Query/OwnedQueryRelationalTestBase.cs |
Adds owned-navigation regression cases. |
test/EFCore.Relational.Specification.Tests/Query/NorthwindCommonTableQueryRelationalTestBase.cs |
Defines shared CTE and fallback tests. |
test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesRelationalTestBase.cs |
Adds captured-query bulk operation tests. |
src/EFCore/Query/QueryableMethodTranslatingExpressionVisitor.cs |
Adds the provider translation hook. |
src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs |
Handles markers and structural fallbacks. |
src/EFCore/Query/Internal/ExpressionTreeFuncletizer.cs |
Names and marks captured queries. |
src/EFCore/Query/Internal/EmbeddedQueryable.cs |
Defines the query marker method. |
src/EFCore/EFCore.baseline.json |
Records the new translation API. |
src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs |
Handles CTE columns and statement ordering. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteSubqueryToJoinRewriter.cs |
Preserves named CTE references. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteApplyFlatteningExpressionVisitor.cs |
Prevents flattening CTE references. |
src/EFCore.Relational/Query/SqlTreePruner.cs |
Coordinates pruning across CTE references. |
src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs |
Stores CTE names and supports pushdown. |
src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs |
Creates CTE sources and guards join pruning. |
src/EFCore.Relational/Query/QuerySqlGenerator.cs |
Hoists, deduplicates, names, and emits CTEs. |
src/EFCore.Relational/EFCore.Relational.baseline.json |
Records relational CTE APIs. |
Review effort: Balanced
| var existing = definitions.FindIndex( | ||
| d => string.Equals(d.OriginalName, name, StringComparison.Ordinal) && d.Normalized.Equals(normalized)); | ||
| if (existing >= 0) | ||
| { | ||
| _commonTableNames[select] = definitions[existing].Name; |
There was a problem hiding this comment.
This is intended: a captured variable names one set, so both references read the same rows, which is also what SQLite and PostgreSQL do for a CTE referenced more than once. Inlining volatile queries would add a fair amount of logic for a rare case, so I'd leave it unless you think otherwise.
| continue; | ||
| } | ||
|
|
||
| var uniqueName = Uniquifier.Uniquify(name, usedNames, maxLength: int.MaxValue); |
There was a problem hiding this comment.
Agreed this is possible in theory, but it needs a variable name over 128 characters. Plumbing the identifier limit into the SQL generator didn't seem worth it for that; happy to add it if you'd prefer.

Fixes #29918
A captured
IQueryablevariable used inside a lambda of another query is now translated to a common table expression named after the variable, as agreed on #26486 (always translate to a CTE).How it works
ExpressionTreeFuncletizerwraps the inlined query inEmbeddedQueryable.Marker(source, name). It's a plain method call, so every visitor visits the embedded query without knowing about the marker.TranslateEmbeddedQueryjust returns the translated source, so non-relational providers behave as before. The relational override pushes it into a subquery carrying the CTE name. A relational provider without CTE support can override it the same way.QuerySqlGeneratorhoists all CTEs to the root statement (SELECT, UPDATE, DELETE), dedupes references to the same definition, and renames a CTE whose name clashes with a table, table alias, table-valued function or identifier in raw SQL.SqlTreePrunerremoves CTE columns no reference uses.SET NOCOUNT OFFbeforeWITH. SQLite's subquery-to-join rewriter and APPLY flattening leave CTE references alone.Not translated to a CTE (inlined as before)
DbSetassigned to anIQueryablevariable..Union(lateOrders)or.Join(lateOrders, ...):Queryablesplices inlateOrders.Expression, so there is no captured variable left.References that need different columns (e.g. owned columns bound on one use only) become separate CTEs.