Skip to content

Commit c003750

Browse files
committed
Guard shared columns of optional owned types bound over single-result 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.
1 parent a6c54b1 commit c003750

3 files changed

Lines changed: 149 additions & 65 deletions

File tree

‎src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs‎

Lines changed: 68 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1334,70 +1334,8 @@ private SqlExpression BindProperty(StructuralTypeReferenceExpression typeReferen
13341334
return jsonQueryExpression.BindProperty(property);
13351335
}
13361336

1337-
var projection = (StructuralTypeProjectionExpression)valueBufferExpression;
1338-
var propertyAccess = projection.BindProperty(property);
1339-
1340-
if (typeReference.StructuralType is not IEntityType entityType
1341-
|| entityType.FindDiscriminatorProperty() != null
1342-
|| entityType.FindPrimaryKey() == null
1343-
|| entityType.GetRootType() != entityType
1344-
|| entityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy)
1345-
{
1346-
return propertyAccess;
1347-
}
1348-
1349-
// Scope to actually-projected tables when known (entity-splitting).
1350-
var table = entityType.GetProjectedQueryMappings(projection.TableMap)
1351-
.Single(e => e.IsSplitEntityTypePrincipal ?? true).Table;
1352-
if (!table.IsOptional(entityType))
1353-
{
1354-
return propertyAccess;
1355-
}
1356-
1357-
// this is optional dependent sharing table
1358-
var nonPrincipalSharedNonPkProperties = entityType.GetNonPrincipalSharedNonPkProperties(table);
1359-
if (nonPrincipalSharedNonPkProperties.Contains(property))
1360-
{
1361-
// The column is not being shared with principal side so we can always use directly
1362-
return propertyAccess;
1363-
}
1364-
1365-
SqlExpression? condition = null;
1366-
// Property is being shared with principal side, so we need to make it conditional access
1367-
var allRequiredNonPkProperties = entityType.GetRequiredNonPkProperties();
1368-
if (allRequiredNonPkProperties.Count > 0)
1369-
{
1370-
condition = allRequiredNonPkProperties.Select(projection.BindColumn)
1371-
.Select(c => _sqlExpressionFactory.NotEqual(c, _sqlExpressionFactory.Constant(null, c.Type)))
1372-
.Aggregate(_sqlExpressionFactory.AndAlso);
1373-
}
1374-
1375-
if (nonPrincipalSharedNonPkProperties.Count != 0
1376-
&& nonPrincipalSharedNonPkProperties.All(p => p.IsNullable()))
1377-
{
1378-
// If all non principal shared properties are nullable then we need additional condition
1379-
var atLeastOneNonNullValueInNullableColumnsCondition = nonPrincipalSharedNonPkProperties
1380-
.Select(projection.BindColumn)
1381-
.Select(c => _sqlExpressionFactory.NotEqual(c, _sqlExpressionFactory.Constant(null, c.Type)))
1382-
.Aggregate(_sqlExpressionFactory.OrElse);
1383-
1384-
condition = condition == null
1385-
? atLeastOneNonNullValueInNullableColumnsCondition
1386-
: _sqlExpressionFactory.AndAlso(condition, atLeastOneNonNullValueInNullableColumnsCondition);
1387-
}
1388-
1389-
if (condition == null)
1390-
{
1391-
// if we cannot compute condition then we just return property access (and hope for the best)
1392-
return propertyAccess;
1393-
}
1394-
1395-
return _sqlExpressionFactory.Case(
1396-
[new CaseWhenClause(condition, propertyAccess)],
1397-
elseResult: null);
1398-
1399-
// We don't do above processing for subquery entity since it comes from after subquery which has been
1400-
// single result so either it is regular entity or a collection which always have their own table.
1337+
return BindProperty(
1338+
(StructuralTypeProjectionExpression)valueBufferExpression, typeReference.StructuralType, property);
14011339
}
14021340

14031341
case { Subquery: { } subquery }:
@@ -1408,7 +1346,8 @@ [new CaseWhenClause(condition, propertyAccess)],
14081346
var projectionBindingExpression = (ProjectionBindingExpression)shaper.ValueBufferExpression;
14091347
var innerProjection = subSelectExpression.GetProjection(projectionBindingExpression) switch
14101348
{
1411-
StructuralTypeProjectionExpression projection => projection.BindProperty(property),
1349+
// An included owned navigation can be an optional dependent sharing its owner's table (see TryBindMember)
1350+
StructuralTypeProjectionExpression projection => BindProperty(projection, typeReference.StructuralType, property),
14121351

14131352
// A JSON complex type bound over a subquery (see BindComplexProperty)
14141353
JsonQueryExpression jsonQuery => jsonQuery.BindProperty(property),
@@ -1426,6 +1365,70 @@ [new CaseWhenClause(condition, propertyAccess)],
14261365
}
14271366
}
14281367

1368+
private SqlExpression BindProperty(StructuralTypeProjectionExpression projection, ITypeBase structuralType, IProperty property)
1369+
{
1370+
var propertyAccess = projection.BindProperty(property);
1371+
1372+
if (structuralType is not IEntityType entityType
1373+
|| entityType.FindDiscriminatorProperty() != null
1374+
|| entityType.FindPrimaryKey() == null
1375+
|| entityType.GetRootType() != entityType
1376+
|| entityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy)
1377+
{
1378+
return propertyAccess;
1379+
}
1380+
1381+
// Scope to actually-projected tables when known (entity-splitting).
1382+
var table = entityType.GetProjectedQueryMappings(projection.TableMap)
1383+
.Single(e => e.IsSplitEntityTypePrincipal ?? true).Table;
1384+
if (!table.IsOptional(entityType))
1385+
{
1386+
return propertyAccess;
1387+
}
1388+
1389+
// this is optional dependent sharing table
1390+
var nonPrincipalSharedNonPkProperties = entityType.GetNonPrincipalSharedNonPkProperties(table);
1391+
if (nonPrincipalSharedNonPkProperties.Contains(property))
1392+
{
1393+
// The column is not being shared with principal side so we can always use directly
1394+
return propertyAccess;
1395+
}
1396+
1397+
SqlExpression? condition = null;
1398+
// Property is being shared with principal side, so we need to make it conditional access
1399+
var allRequiredNonPkProperties = entityType.GetRequiredNonPkProperties();
1400+
if (allRequiredNonPkProperties.Count > 0)
1401+
{
1402+
condition = allRequiredNonPkProperties.Select(projection.BindColumn)
1403+
.Select(c => _sqlExpressionFactory.NotEqual(c, _sqlExpressionFactory.Constant(null, c.Type)))
1404+
.Aggregate(_sqlExpressionFactory.AndAlso);
1405+
}
1406+
1407+
if (nonPrincipalSharedNonPkProperties.Count != 0
1408+
&& nonPrincipalSharedNonPkProperties.All(p => p.IsNullable()))
1409+
{
1410+
// If all non principal shared properties are nullable then we need additional condition
1411+
var atLeastOneNonNullValueInNullableColumnsCondition = nonPrincipalSharedNonPkProperties
1412+
.Select(projection.BindColumn)
1413+
.Select(c => _sqlExpressionFactory.NotEqual(c, _sqlExpressionFactory.Constant(null, c.Type)))
1414+
.Aggregate(_sqlExpressionFactory.OrElse);
1415+
1416+
condition = condition == null
1417+
? atLeastOneNonNullValueInNullableColumnsCondition
1418+
: _sqlExpressionFactory.AndAlso(condition, atLeastOneNonNullValueInNullableColumnsCondition);
1419+
}
1420+
1421+
if (condition == null)
1422+
{
1423+
// if we cannot compute condition then we just return property access (and hope for the best)
1424+
return propertyAccess;
1425+
}
1426+
1427+
return _sqlExpressionFactory.Case(
1428+
[new CaseWhenClause(condition, propertyAccess)],
1429+
elseResult: null);
1430+
}
1431+
14291432
private Expression BindComplexProperty(StructuralTypeReferenceExpression typeReference, IComplexProperty complexProperty)
14301433
{
14311434
switch (typeReference)

‎test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2206,6 +2206,64 @@ public override void ToJsonTyped(Utf8JsonWriter writer, TagCode value)
22062206

22072207
#endregion
22082208

2209+
#region 36296
2210+
2211+
// Details is an optional dependent whose Name shares a column with its owner, so the column holds the owner's value when Details
2212+
// is absent; binding Details.Name on the element of a grouping must check that Details is present, as it does without a subquery.
2213+
[Theory, MemberData(nameof(IsAsyncData))]
2214+
public virtual async Task Optional_owned_property_sharing_owner_column_on_GroupBy_element(bool async)
2215+
{
2216+
var contextFactory = await InitializeNonSharedTest<Context36296>(seed: c => c.SeedAsync());
2217+
using var context = contextFactory.CreateDbContext();
2218+
ClearLog();
2219+
2220+
var query = context.Set<Context36296.Product>()
2221+
.GroupBy(e => e.Category)
2222+
.Select(g => g.OrderBy(e => e.Id).First(e => e.Id > 0))
2223+
.Where(e => e.Details!.Name == "Shared")
2224+
.Select(e => e.Category);
2225+
2226+
var result = async ? await query.ToListAsync() : query.ToList();
2227+
2228+
Assert.Equal("With details", Assert.Single(result));
2229+
}
2230+
2231+
// Protected so that it can be used by inheriting tests, and so that things like unused setters are not removed.
2232+
protected class Context36296(DbContextOptions options) : DbContext(options)
2233+
{
2234+
protected override void OnModelCreating(ModelBuilder modelBuilder)
2235+
=> modelBuilder.Entity<Product>(b =>
2236+
{
2237+
b.Property(e => e.Name).HasColumnName("Name");
2238+
b.OwnsOne(e => e.Details, d => d.Property(e => e.Name).HasColumnName("Name"));
2239+
});
2240+
2241+
public Task SeedAsync()
2242+
{
2243+
AddRange(
2244+
new Product { Category = "With details", Name = "Shared", Details = new Details { Name = "Shared", Weight = 1 } },
2245+
new Product { Category = "Without details", Name = "Shared" });
2246+
2247+
return SaveChangesAsync();
2248+
}
2249+
2250+
public class Product
2251+
{
2252+
public int Id { get; set; }
2253+
public string Category { get; set; } = null!;
2254+
public string Name { get; set; } = null!;
2255+
public Details? Details { get; set; }
2256+
}
2257+
2258+
public class Details
2259+
{
2260+
public string? Name { get; set; }
2261+
public int Weight { get; set; }
2262+
}
2263+
}
2264+
2265+
#endregion
2266+
22092267
protected override DbContextOptionsBuilder AddNonSharedOptions(DbContextOptionsBuilder builder)
22102268
=> base.AddNonSharedOptions(builder).ConfigureWarnings(c => c
22112269
.Log(RelationalEventId.OptionalDependentWithoutIdentifyingPropertyWarning)

‎test/EFCore.SqlServer.FunctionalTests/Query/OwnedEntityQuerySqlServerTest.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,29 @@ GROUP BY [o].[Region]
744744
""");
745745
}
746746

747+
public override async Task Optional_owned_property_sharing_owner_column_on_GroupBy_element(bool async)
748+
{
749+
await base.Optional_owned_property_sharing_owner_column_on_GroupBy_element(async);
750+
751+
AssertSql(
752+
"""
753+
SELECT (
754+
SELECT TOP(1) [p1].[Category]
755+
FROM [Product] AS [p1]
756+
WHERE [p].[Category] = [p1].[Category] AND [p1].[Id] > 0
757+
ORDER BY [p1].[Id])
758+
FROM [Product] AS [p]
759+
GROUP BY [p].[Category]
760+
HAVING (
761+
SELECT TOP(1) CASE
762+
WHEN [p0].[Details_Weight] IS NOT NULL THEN [p0].[Name]
763+
END
764+
FROM [Product] AS [p0]
765+
WHERE [p].[Category] = [p0].[Category] AND [p0].[Id] > 0
766+
ORDER BY [p0].[Id]) = N'Shared'
767+
""");
768+
}
769+
747770
public override async Task Owned_collection_select_many_without_result_selector(bool async)
748771
{
749772
await base.Owned_collection_select_many_without_result_selector(async);

0 commit comments

Comments
 (0)