Skip to content

Commit a281882

Browse files
ajcvickersclaude
andcommitted
Translate primitive collections projected through set operations
Fixes #33258 After a set operation (Concat, Union, etc.) over primitive collection columns, the collection is projected out of a subquery and the PrimitiveCollectionReference that kept it queryable is lost. The AsQueryable added during normalization was then stripped, leaving an untranslatable Enumerable.Contains/Count/etc. Preserve the AsQueryable in navigation expansion for such projected primitive collections, and translate the column as a collection in the relational translator. Adds spec tests with overrides for Sqlite, SQL Server (including JSON type and old compatibility levels) and Cosmos. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 867bf0e commit a281882

8 files changed

Lines changed: 642 additions & 0 deletions

File tree

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,19 @@ private Expression VisitMethodCallCore(MethodCallExpression methodCallExpression
308308

309309
var translated = base.VisitMethodCall(methodCallExpression);
310310

311+
// AsQueryable over a primitive collection column that was projected out of a subquery, e.g. after a set operation (#33258).
312+
// Unlike a property of an entity, it isn't bound by TranslateMemberAccess, so translate the column as a collection here.
313+
if (translated == QueryCompilationContext.NotTranslatedExpression
314+
&& method.IsGenericMethod
315+
&& method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable
316+
&& methodCallExpression.Arguments[0] is not MethodCallExpression // EF.Property etc. are handled by the base class
317+
&& _sqlTranslator.Visit(methodCallExpression.Arguments[0]) is ColumnExpression { TypeMapping.ElementTypeMapping: not null } column
318+
&& TranslatePrimitiveCollection(column, property: null, _sqlAliasManager.GenerateTableAlias(column.Name))
319+
is { } columnCollection)
320+
{
321+
return columnCollection;
322+
}
323+
311324
// For Contains over a collection parameter, if the provider hasn't implemented TranslateCollection (e.g. OPENJSON on SQL
312325
// Server), we need to fall back to the previous IN translation.
313326
if (translated == QueryCompilationContext.NotTranslatedExpression

‎src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -849,6 +849,15 @@ when QueryableMethods.IsSumWithSelector(method):
849849
navigationTreeExpression);
850850
}
851851

852+
if (IsProjectedPrimitiveCollection(firstArgument, out var projectedElementType))
853+
{
854+
// The collection was projected out of a subquery (e.g. by a set operation), which loses the
855+
// PrimitiveCollectionReference that would otherwise keep the collection queryable, so preserve the AsQueryable (#33258).
856+
return Expression.Call(
857+
QueryableMethods.AsQueryable.MakeGenericMethod(projectedElementType),
858+
firstArgument);
859+
}
860+
852861
return UnwrapCollectionMaterialization(firstArgument);
853862
}
854863

@@ -1561,6 +1570,27 @@ private NavigationExpansionExpression ProcessSelectMany(
15611570
throw new InvalidOperationException(CoreStrings.TranslationFailed(collectionSelector.Print()));
15621571
}
15631572

1573+
// An array or IList of non-entity elements that is either the element of a projection, or a member of an element that was
1574+
// projected into an anonymous type. Entity collections are excluded; they're navigations, not primitive collections.
1575+
private bool IsProjectedPrimitiveCollection(Expression expression, out Type elementType)
1576+
{
1577+
elementType = null!;
1578+
1579+
if (expression is not (NavigationTreeExpression { Value.NodeType: ExpressionType.Default }
1580+
or MemberExpression { Expression: NavigationTreeExpression { Value.NodeType: ExpressionType.New or ExpressionType.Default } })
1581+
|| expression.Type == typeof(byte[])
1582+
|| expression.Type.TryGetElementType(typeof(IQueryable<>)) != null
1583+
|| expression.Type.TryGetElementType(typeof(IEnumerable<>)) is not { } candidate
1584+
|| !(expression.Type.IsArray || typeof(IList<>).MakeGenericType(candidate).IsAssignableFrom(expression.Type))
1585+
|| _queryCompilationContext.Model.FindEntityType(candidate) != null)
1586+
{
1587+
return false;
1588+
}
1589+
1590+
elementType = candidate;
1591+
return true;
1592+
}
1593+
15641594
private NavigationExpansionExpression ProcessSetOperation(
15651595
NavigationExpansionExpression outerSource,
15661596
MethodInfo genericMethod,

‎test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1761,6 +1761,70 @@ FROM root c
17611761
""");
17621762
}
17631763

1764+
public override async Task Concat_of_column_collections_then_Contains()
1765+
{
1766+
// Set operations and DISTINCT over whole documents aren't supported
1767+
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains);
1768+
1769+
AssertSql();
1770+
}
1771+
1772+
public override async Task Union_of_column_collections_then_Contains()
1773+
{
1774+
// Set operations and DISTINCT over whole documents aren't supported
1775+
await AssertTranslationFailed(base.Union_of_column_collections_then_Contains);
1776+
1777+
AssertSql();
1778+
}
1779+
1780+
public override async Task Concat_of_anonymous_types_with_column_collection_then_Contains()
1781+
{
1782+
// Set operations and DISTINCT over whole documents aren't supported
1783+
await AssertTranslationFailed(base.Concat_of_anonymous_types_with_column_collection_then_Contains);
1784+
1785+
AssertSql();
1786+
}
1787+
1788+
public override async Task Concat_of_column_collections_then_Where_Count()
1789+
{
1790+
// Set operations and DISTINCT over whole documents aren't supported
1791+
await AssertTranslationFailed(base.Concat_of_column_collections_then_Where_Count);
1792+
1793+
AssertSql();
1794+
}
1795+
1796+
public override async Task Concat_of_string_column_collections_then_Contains()
1797+
{
1798+
// Set operations and DISTINCT over whole documents aren't supported
1799+
await AssertTranslationFailed(base.Concat_of_string_column_collections_then_Contains);
1800+
1801+
AssertSql();
1802+
}
1803+
1804+
public override async Task Concat_of_column_collections_then_Contains_parameter()
1805+
{
1806+
// Set operations and DISTINCT over whole documents aren't supported
1807+
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains_parameter);
1808+
1809+
AssertSql();
1810+
}
1811+
1812+
public override async Task Concat_of_column_collections_then_Contains_then_Select_Count()
1813+
{
1814+
// Set operations and DISTINCT over whole documents aren't supported
1815+
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains_then_Select_Count);
1816+
1817+
AssertSql();
1818+
}
1819+
1820+
public override async Task Distinct_of_column_collection_then_Contains()
1821+
{
1822+
// Set operations and DISTINCT over whole documents aren't supported
1823+
await AssertTranslationFailed(base.Distinct_of_column_collection_then_Contains);
1824+
1825+
AssertSql();
1826+
}
1827+
17641828
public override async Task Column_collection_Distinct()
17651829
{
17661830
// TODO: Subquery pushdown, #33968

‎test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1379,6 +1379,84 @@ public virtual Task Inline_collection_Join_ordered_column_collection()
13791379
=> AssertQuery(ss => ss.Set<PrimitiveCollectionsEntity>()
13801380
.Where(c => new[] { 11, 111 }.Join(c.Ints, i => i, j => j, (i, j) => new { I = i, J = j }).Count() == 2));
13811381

1382+
[Fact] // #33258
1383+
public virtual Task Concat_of_column_collections_then_Contains()
1384+
=> AssertQuery(
1385+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints)
1386+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints))
1387+
.Where(x => x.Contains(10)),
1388+
elementSorter: e => string.Join(",", e),
1389+
elementAsserter: (e, a) => Assert.Equal(e, a));
1390+
1391+
[Fact] // #33258
1392+
public virtual Task Union_of_column_collections_then_Contains()
1393+
=> AssertQuery(
1394+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints)
1395+
.Union(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints))
1396+
.Where(x => x.Contains(10)),
1397+
elementSorter: e => string.Join(",", e),
1398+
elementAsserter: (e, a) => Assert.Equal(e, a));
1399+
1400+
[Fact] // #33258
1401+
public virtual Task Concat_of_anonymous_types_with_column_collection_then_Contains()
1402+
=> AssertQuery(
1403+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => new { c.Id, c.Ints })
1404+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => new { c.Id, c.Ints }))
1405+
.Where(x => x.Ints.Contains(10)),
1406+
elementSorter: e => e.Id,
1407+
elementAsserter: (e, a) =>
1408+
{
1409+
Assert.Equal(e.Id, a.Id);
1410+
Assert.Equal(e.Ints, a.Ints);
1411+
});
1412+
1413+
[Fact] // #33258
1414+
public virtual Task Concat_of_column_collections_then_Where_Count()
1415+
=> AssertQuery(
1416+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints)
1417+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints))
1418+
.Where(x => x.Count(i => i > 10) == 2),
1419+
elementSorter: e => string.Join(",", e),
1420+
elementAsserter: (e, a) => Assert.Equal(e, a));
1421+
1422+
[Fact] // #33258
1423+
public virtual Task Concat_of_string_column_collections_then_Contains()
1424+
=> AssertQuery(
1425+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Strings)
1426+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Strings))
1427+
.Where(x => x.Contains("10")),
1428+
elementSorter: e => string.Join(",", e),
1429+
elementAsserter: (e, a) => Assert.Equal(e, a));
1430+
1431+
[Fact] // #33258
1432+
public virtual Task Concat_of_column_collections_then_Contains_parameter()
1433+
{
1434+
var value = 10;
1435+
1436+
return AssertQuery(
1437+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints)
1438+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints))
1439+
.Where(x => x.Contains(value)),
1440+
elementSorter: e => string.Join(",", e),
1441+
elementAsserter: (e, a) => Assert.Equal(e, a));
1442+
}
1443+
1444+
[Fact] // #33258
1445+
public virtual Task Concat_of_column_collections_then_Contains_then_Select_Count()
1446+
=> AssertQuery(
1447+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints)
1448+
.Concat(ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints))
1449+
.Where(x => x.Contains(10))
1450+
.Select(x => x.Count(i => i > 1)));
1451+
1452+
[Fact] // #33258
1453+
public virtual Task Distinct_of_column_collection_then_Contains()
1454+
=> AssertQuery(
1455+
ss => ss.Set<PrimitiveCollectionsEntity>().Select(c => c.Ints).Distinct()
1456+
.Where(x => x.Contains(10)),
1457+
elementSorter: e => string.Join(",", e),
1458+
elementAsserter: (e, a) => Assert.Equal(e, a));
1459+
13821460
[Fact]
13831461
public virtual Task Parameter_collection_Concat_column_collection()
13841462
{

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1688,6 +1688,30 @@ public override Task Column_collection_Join_parameter_collection()
16881688
public override Task Inline_collection_Join_ordered_column_collection()
16891689
=> AssertCompatibilityLevelTooLow(() => base.Inline_collection_Join_ordered_column_collection());
16901690

1691+
public override Task Concat_of_column_collections_then_Contains()
1692+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_column_collections_then_Contains());
1693+
1694+
public override Task Union_of_column_collections_then_Contains()
1695+
=> AssertCompatibilityLevelTooLow(() => base.Union_of_column_collections_then_Contains());
1696+
1697+
public override Task Concat_of_anonymous_types_with_column_collection_then_Contains()
1698+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_anonymous_types_with_column_collection_then_Contains());
1699+
1700+
public override Task Concat_of_column_collections_then_Where_Count()
1701+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_column_collections_then_Where_Count());
1702+
1703+
public override Task Concat_of_string_column_collections_then_Contains()
1704+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_string_column_collections_then_Contains());
1705+
1706+
public override Task Concat_of_column_collections_then_Contains_parameter()
1707+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_column_collections_then_Contains_parameter());
1708+
1709+
public override Task Concat_of_column_collections_then_Contains_then_Select_Count()
1710+
=> AssertCompatibilityLevelTooLow(() => base.Concat_of_column_collections_then_Contains_then_Select_Count());
1711+
1712+
public override Task Distinct_of_column_collection_then_Contains()
1713+
=> AssertCompatibilityLevelTooLow(() => base.Distinct_of_column_collection_then_Contains());
1714+
16911715
public override Task Parameter_collection_Concat_column_collection()
16921716
=> AssertCompatibilityLevelTooLow(() => base.Parameter_collection_Concat_column_collection());
16931717

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

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using Microsoft.Data.SqlClient;
45
using Xunit.Sdk;
56

67
namespace Microsoft.EntityFrameworkCore.Query;
@@ -24,6 +25,138 @@ public PrimitiveCollectionsQuerySqlServerJsonTypeTest(
2425
public virtual void Check_all_tests_overridden()
2526
=> TestHelpers.AssertAllMethodsOverridden(GetType());
2627

28+
public override async Task Concat_of_column_collections_then_Contains()
29+
{
30+
await base.Concat_of_column_collections_then_Contains();
31+
32+
AssertSql(
33+
"""
34+
SELECT [u].[Ints]
35+
FROM (
36+
SELECT [p].[Ints]
37+
FROM [PrimitiveCollectionsEntity] AS [p]
38+
UNION ALL
39+
SELECT [p0].[Ints]
40+
FROM [PrimitiveCollectionsEntity] AS [p0]
41+
) AS [u]
42+
WHERE JSON_CONTAINS([u].[Ints], 10) = 1
43+
""");
44+
}
45+
46+
public override async Task Union_of_column_collections_then_Contains()
47+
{
48+
// The json data type isn't comparable, so it can't be used with UNION or DISTINCT (UNION ALL is fine)
49+
await Assert.ThrowsAsync<SqlException>(() => base.Union_of_column_collections_then_Contains());
50+
51+
AssertSql();
52+
}
53+
54+
public override async Task Concat_of_anonymous_types_with_column_collection_then_Contains()
55+
{
56+
await base.Concat_of_anonymous_types_with_column_collection_then_Contains();
57+
58+
AssertSql(
59+
"""
60+
SELECT [u].[Id], [u].[Ints]
61+
FROM (
62+
SELECT [p].[Id], [p].[Ints]
63+
FROM [PrimitiveCollectionsEntity] AS [p]
64+
UNION ALL
65+
SELECT [p0].[Id], [p0].[Ints]
66+
FROM [PrimitiveCollectionsEntity] AS [p0]
67+
) AS [u]
68+
WHERE JSON_CONTAINS([u].[Ints], 10) = 1
69+
""");
70+
}
71+
72+
public override async Task Concat_of_column_collections_then_Where_Count()
73+
{
74+
await base.Concat_of_column_collections_then_Where_Count();
75+
76+
AssertSql(
77+
"""
78+
SELECT [u].[Ints]
79+
FROM (
80+
SELECT [p].[Ints]
81+
FROM [PrimitiveCollectionsEntity] AS [p]
82+
UNION ALL
83+
SELECT [p0].[Ints]
84+
FROM [PrimitiveCollectionsEntity] AS [p0]
85+
) AS [u]
86+
WHERE (
87+
SELECT COUNT(*)
88+
FROM OPENJSON([u].[Ints]) WITH ([value] int '$') AS [i]
89+
WHERE [i].[value] > 10) = 2
90+
""");
91+
}
92+
93+
public override async Task Concat_of_string_column_collections_then_Contains()
94+
{
95+
await base.Concat_of_string_column_collections_then_Contains();
96+
97+
AssertSql(
98+
"""
99+
SELECT [u].[Strings]
100+
FROM (
101+
SELECT [p].[Strings]
102+
FROM [PrimitiveCollectionsEntity] AS [p]
103+
UNION ALL
104+
SELECT [p0].[Strings]
105+
FROM [PrimitiveCollectionsEntity] AS [p0]
106+
) AS [u]
107+
WHERE JSON_CONTAINS([u].[Strings], N'10') = 1
108+
""");
109+
}
110+
111+
public override async Task Concat_of_column_collections_then_Contains_parameter()
112+
{
113+
await base.Concat_of_column_collections_then_Contains_parameter();
114+
115+
AssertSql(
116+
"""
117+
@value='10'
118+
119+
SELECT [u].[Ints]
120+
FROM (
121+
SELECT [p].[Ints]
122+
FROM [PrimitiveCollectionsEntity] AS [p]
123+
UNION ALL
124+
SELECT [p0].[Ints]
125+
FROM [PrimitiveCollectionsEntity] AS [p0]
126+
) AS [u]
127+
WHERE JSON_CONTAINS([u].[Ints], @value) = 1
128+
""");
129+
}
130+
131+
public override async Task Concat_of_column_collections_then_Contains_then_Select_Count()
132+
{
133+
await base.Concat_of_column_collections_then_Contains_then_Select_Count();
134+
135+
AssertSql(
136+
"""
137+
SELECT (
138+
SELECT COUNT(*)
139+
FROM OPENJSON([u].[Ints]) WITH ([value] int '$') AS [i]
140+
WHERE [i].[value] > 1)
141+
FROM (
142+
SELECT [p].[Ints]
143+
FROM [PrimitiveCollectionsEntity] AS [p]
144+
UNION ALL
145+
SELECT [p0].[Ints]
146+
FROM [PrimitiveCollectionsEntity] AS [p0]
147+
) AS [u]
148+
WHERE JSON_CONTAINS([u].[Ints], 10) = 1
149+
""");
150+
}
151+
152+
public override async Task Distinct_of_column_collection_then_Contains()
153+
{
154+
// The json data type isn't comparable, so it can't be used with UNION or DISTINCT (UNION ALL is fine)
155+
await Assert.ThrowsAsync<SqlException>(() => base.Distinct_of_column_collection_then_Contains());
156+
157+
AssertSql();
158+
}
159+
27160
public override async Task Inline_collection_with_single_parameter_element_Contains()
28161
{
29162
await base.Inline_collection_with_single_parameter_element_Contains();

0 commit comments

Comments
 (0)