Skip to content

Bind complex properties over single-result subqueries - #39763

Open
jeremy-morren wants to merge 5 commits into
dotnet:mainfrom
jeremy-morren:complex-property-binding-over-subquery
Open

jeremy-morren wants to merge 5 commits into
dotnet:mainfrom
jeremy-morren:complex-property-binding-over-subquery

Conversation

@jeremy-morren

@jeremy-morren jeremy-morren commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Add translation for complex properties and owned navigations on an entity returned by a single-result subquery, such as GroupBy(...).Select(g => g.First(...)):

  • Complex properties: binds the complex property inside a copy of the subquery and projects its type from there, so its properties become scalar subqueries. Covers table-split and JSON complex types, including nested and optional complex properties. Previously threw Complex property binding over a subquery.
  • Complex collections: fails translation instead of throwing Complex collection binding over a subquery, so projecting one falls back to client evaluation and other uses get the standard translation error.
  • Entities that include navigations: Where and OrderBy on such an element failed to translate when the entity includes navigations (e.g. owned types), because the subquery's shaper was wrapped in IncludeExpressions. The includes are unwrapped, and an included reference navigation is bound over the same subquery.
public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public bool Shipped { get; set; }
    public Address ShippingAddress { get; set; }   // complex
    public List<Line> Lines { get; set; }          // complex collection
    public Address BillingAddress { get; set; }    // owned
}

public class Address
{
    public string City { get; set; }
}

public class Line
{
    public int Quantity { get; set; }
}

modelBuilder.Entity<Order>(b =>
{
    b.ComplexProperty(o => o.ShippingAddress); // or .ToJson()
    b.ComplexCollection(o => o.Lines, l => l.ToJson());
    b.OwnsOne(o => o.BillingAddress);
});

var lastShippedOrders = context.Orders
    .GroupBy(o => o.CustomerId)
    .Select(g => g.OrderByDescending(o => o.Id).First(o => o.Shipped));

// Complex property: translated
await lastShippedOrders.Select(o => o.ShippingAddress.City).ToListAsync();

// Complex collection: evaluated on the client
await lastShippedOrders.Select(o => o.Lines).ToListAsync();

// Owned navigation: translated
await lastShippedOrders.Where(o => o.BillingAddress.City == "Paris").ToListAsync();

Comparing such a complex property to null or to another value still throws SubqueryOverComplexTypesNotSupported, since it would duplicate the subquery (#32228).

The GroupBy element tests are in the shared associations test base, so they run for complex, owned and navigation mappings.

Implements some of #36296 (Subqueries: complex property binding over subquery).

@jeremy-morren
jeremy-morren requested a review from a team as a code owner November 22, 2026 23:22
@jeremy-morren
jeremy-morren force-pushed the complex-property-binding-over-subquery branch from 159c597 to 842f3a1 Compare November 23, 2026 13:25
@AndriySvyryd
AndriySvyryd requested a balanced review from Copilot November 24, 2026 00:18
@jeremy-morren
jeremy-morren force-pushed the complex-property-binding-over-subquery branch from 842f3a1 to 3d36469 Compare November 24, 2026 00:18
Accessing a complex property on an entity produced by a single-result
subquery (e.g. GroupBy(...).Select(g => g.First(...)).Select(e => e.Complex))
threw "Complex property binding over a subquery". Bind the complex property
inside a copy of the subquery and project its type from there, so that its
properties are bound as scalar subqueries. Handles table-split and JSON
complex types, including nested complex properties.
A complex collection accessed on an entity produced by a single-result
subquery threw "Complex collection binding over a subquery". Fail
translation instead, so that projecting the collection falls back to
client evaluation and other uses report the standard translation error.
@jeremy-morren
jeremy-morren force-pushed the complex-property-binding-over-subquery branch from 3d36469 to 9553587 Compare November 24, 2026 00:23

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Direct column binding bypasses the optional-owned presence guard, causing filters to incorrectly retain groups when an absent owned instance shares a column with its owner.

1 open issue
What changed in this PR

Extends EF Core’s relational query translation to bind complex properties and included reference navigations over single-result subqueries, advancing #36296 while leaving complex-type equality over subqueries unsupported.

Changes:

  • Binds nested and optional complex properties through cloned subquery projections.
  • Unwraps included navigations and allows client evaluation of unsupported complex-collection projections.
  • Adds shared regression tests, SQL Server baselines, and Cosmos translation-failure expectations.
File Description
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​OwnedTableSplitting/​OwnedTableSplittingMiscellaneousSqlServerTest.cs Adds filtering and ordering baselines for table-split owned types.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​OwnedNavigations/​OwnedNavigationsMiscellaneousSqlServerTest.cs Adds owned-navigation filtering and ordering baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​OwnedJson/​OwnedJsonMiscellaneousSqlServerTest.cs Covers owned JSON with text and native JSON storage.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​OwnedComplexProperties/​OwnedComplexPropertiesMiscellaneousSqlServerTest.cs Covers owned types containing complex properties.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​Navigations/​NavigationsMiscellaneousSqlServerTest.cs Adds regular-navigation filtering and ordering baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​ComplexTableSplitting/​ComplexTableSplittingProjectionSqlServerTest.cs Covers nested and optional complex-property projections.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​ComplexTableSplitting/​ComplexTableSplittingMiscellaneousSqlServerTest.cs Adds table-split complex-property filtering and ordering baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​ComplexJson/​ComplexJsonProjectionSqlServerTest.cs Covers JSON scalar projections and collection fallback.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Associations/​ComplexJson/​ComplexJsonMiscellaneousSqlServerTest.cs Adds complex JSON filtering and ordering baselines.
test/​EFCore.Specification.Tests/​Query/​Associations/​ComplexProperties/​ComplexPropertiesProjectionTestBase.cs Defines shared complex-property projection tests.
test/​EFCore.Specification.Tests/​Query/​Associations/​AssociationsMiscellaneousTestBase.cs Defines shared GroupBy element filtering and ordering tests.
test/​EFCore.Relational.Specification.Tests/​Query/​Associations/​ComplexJson/​ComplexJsonProjectionRelationalTestBase.cs Tests collection and collection-count projections.
test/​EFCore.Cosmos.FunctionalTests/​Query/​Associations/​OwnedNavigations/​OwnedNavigationsMiscellaneousCosmosTest.cs Records unsupported owned-navigation GroupBy queries.
test/​EFCore.Cosmos.FunctionalTests/​Query/​Associations/​OwnedComplexProperties/​OwnedComplexPropertiesMiscellaneousCosmosTest.cs Records unsupported owned-complex GroupBy queries.
test/​EFCore.Cosmos.FunctionalTests/​Query/​Associations/​ComplexProperties/​ComplexPropertiesProjectionCosmosTest.cs Records unsupported complex-property projections.
test/​EFCore.Cosmos.FunctionalTests/​Query/​Associations/​ComplexProperties/​ComplexPropertiesMiscellaneousCosmosTest.cs Records unsupported complex-property filtering and ordering.
src/​EFCore.Relational/​Query/​RelationalSqlTranslatingExpressionVisitor.cs Implements subquery property and included-navigation binding.

Review effort: Balanced

@jeremy-morren

jeremy-morren commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Changes since the last update, all on an entity returned by a single-result subquery such as GroupBy(...).Select(g => g.First(...)):

  • A property of an optional owned type sharing a column with its owner (c003750, from Copilot's review) is now guarded on the owned instance being present (CASE WHEN ... IS NOT NULL THEN ... END), as it is without a subquery. When the owned instance was absent, the column held the owner's value. Test: Optional_owned_property_sharing_owner_column_on_GroupBy_element.
  • Comparing a JSON owned navigation to null (a7e93f6) checked the values in the document, so a document whose values are all null was treated as absent. It now checks the document itself in the subquery (IS NULL / IS NOT NULL). Test: Optional_owned_json_compared_to_null_on_GroupBy_element.
  • A primitive collection of a JSON complex type (a7e93f6), e.g. .Where(e => e.RequiredAssociate.Ints.Any(i => i == 2)), threw IndexOutOfRangeException while generating the table alias on SQLite and on SQL Server without the json type, since the subquery's projection has no alias. The alias is now derived from the JSON property. Test: Any_predicate_on_GroupBy_First.

The binding over the subquery and the presence check are each shared in a helper, so the subquery and non-subquery paths use the same code.

…avigations

Composing a Where or OrderBy over an entity produced by a single-result
subquery (e.g. GroupBy(...).Select(g => g.First(...)).Where(...)) failed to
translate when the entity includes navigations, such as owned types or
auto-included navigations: the subquery's shaper was wrapped in
IncludeExpressions. Unwrap the includes, and bind an included reference
navigation over the same subquery, projecting the navigation's target.

Moves the GroupBy element tests to the shared associations test base, so
that they run for complex types, owned types and navigations.
… subqueries

An owned navigation included by a single-result subquery (e.g. g.First(...).Details)
can be an optional dependent that shares a column with its owner. Binding such a
property read the column directly, so a filter saw the owner's value when the owned
instance was absent. Apply the same presence check as for properties bound without
a subquery, by sharing it in a helper.
…-result subqueries

Comparing a JSON owned navigation of an entity returned by a single-result
subquery to null checked the values in the document, so a document whose
values are all null was treated as absent. Check the document itself over
the subquery instead.

Querying a primitive collection of a JSON complex type on such an entity
threw while generating the table alias, since the scalar subquery's
projection has no alias. Derive the alias from the projected JSON property
instead.
@jeremy-morren
jeremy-morren force-pushed the complex-property-binding-over-subquery branch from e6908ad to a7e93f6 Compare November 27, 2026 01:34
Copilot AI balanced review requested due to automatic review settings November 27, 2026 01:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Nested owned-JSON predicates still fail after grouped First projections because binding relies on pruned includes, and the new complex-property binding path lacks precompiled-query regression coverage.

2 open issues
1 resolved since last review

Review effort: Balanced

Comment on lines +1307 to +1308
&& includedNavigations.TryGetValue(navigation, out var navigationExpression)
&& Visit(subquery.UpdateShaperExpression(navigationExpression)) is StructuralTypeReferenceExpression navigationReference)
Comment on lines +1502 to +1506
subquery = subquery.Update(
subSelectExpression,
new RelationalStructuralTypeShaperExpression(
complexProperty.ComplexType,
new ProjectionBindingExpression(subSelectExpression, projectionMember, typeof(ValueBuffer)),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants