From 47f4138202f6b64bd2ecc5301d9dd92ed137f509 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 15 Dec 2025 10:34:52 +0100 Subject: [PATCH] Fix uncorrelated parameterized collections in compiled queries Fixes #37370 --- .../RelationalTypeMappingPostprocessor.cs | 26 ++++++++-- .../SqlServerTypeMappingPostprocessor.cs | 48 ++++++++++++------- .../PrimitiveCollectionsQueryCosmosTest.cs | 14 ++++++ .../PrimitiveCollectionsQueryTestBase.cs | 10 ++++ ...imitiveCollectionsQueryOldSqlServerTest.cs | 17 +++++++ ...imitiveCollectionsQuerySqlServer160Test.cs | 17 +++++++ ...veCollectionsQuerySqlServerJsonTypeTest.cs | 17 +++++++ .../PrimitiveCollectionsQuerySqlServerTest.cs | 17 +++++++ .../PrimitiveCollectionsQuerySqliteTest.cs | 17 +++++++ 9 files changed, 162 insertions(+), 21 deletions(-) diff --git a/src/EFCore.Relational/Query/RelationalTypeMappingPostprocessor.cs b/src/EFCore.Relational/Query/RelationalTypeMappingPostprocessor.cs index 07ebd1da061..c99d57e7f4e 100644 --- a/src/EFCore.Relational/Query/RelationalTypeMappingPostprocessor.cs +++ b/src/EFCore.Relational/Query/RelationalTypeMappingPostprocessor.cs @@ -175,12 +175,28 @@ protected virtual ValuesExpression ApplyTypeMappingsOnValuesExpression(ValuesExp // VALUES over a values parameter (i.e. a parameter representing the entire collection, that will be constantized into the SQL // later). Apply the inferred type mapping on the parameter. - case { ValuesParameter: { TypeMapping: null } valuesParameter } - when inferredTypeMappings[1] is { } elementTypeMapping: + case { ValuesParameter: { TypeMapping: null } valuesParameter }: { - if (RelationalDependencies.TypeMappingSource.FindMapping( - valuesParameter.Type, QueryCompilationContext.Model, elementTypeMapping) is not - { ElementTypeMapping: not null } collectionParameterTypeMapping) + RelationalTypeMapping? collectionParameterTypeMapping; + + if (inferredTypeMappings[1] is { } elementTypeMapping) + { + // In the usual case, some operation performed against the elements of the collection (e.g. comparison to a column) provides us with + // an element type mapping; infer the collection's type mapping from that. + collectionParameterTypeMapping = RelationalDependencies.TypeMappingSource.FindMapping( + valuesParameter.Type, QueryCompilationContext.Model, elementTypeMapping); + } + else + { + // We have no inferred type mapping for the element type. This means that there was nothing in the query done + // against the elements of the collection (e.g. comparison to a column), which tells us what type mapping it is. + // In normal circumstances, such an expression would get client-evaluated in the funceltizer (no reference to a + // column/database-side object), but with compiled queries the collection parameter gets preserved as-is. + // The only thing we can do is apply the default type mapping. + collectionParameterTypeMapping = RelationalDependencies.TypeMappingSource.FindMapping(valuesParameter.Type, QueryCompilationContext.Model); + } + + if (collectionParameterTypeMapping is not { ElementTypeMapping: not null }) { throw new UnreachableException("A RelationalTypeMapping collection type mapping could not be found"); } diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs index 9316ed18b72..472738a4f13 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs @@ -43,8 +43,7 @@ protected override Expression VisitExtension(Expression expression) => expression switch { SqlServerOpenJsonExpression openJsonExpression - when TryGetInferredTypeMapping(openJsonExpression.Alias, "value", out var typeMapping) - => ApplyTypeMappingsOnOpenJsonExpression(openJsonExpression, [typeMapping]), + => ApplyTypeMappingsOnOpenJsonExpression(openJsonExpression), _ => base.VisitExtension(expression) }; @@ -55,13 +54,8 @@ when TryGetInferredTypeMapping(openJsonExpression.Alias, "value", out var typeMa /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - protected virtual SqlServerOpenJsonExpression ApplyTypeMappingsOnOpenJsonExpression( - SqlServerOpenJsonExpression openJsonExpression, - IReadOnlyList typeMappings) + protected virtual SqlServerOpenJsonExpression ApplyTypeMappingsOnOpenJsonExpression(SqlServerOpenJsonExpression openJsonExpression) { - Check.DebugAssert(typeMappings.Count == 1); - var elementTypeMapping = typeMappings[0]; - // Constant queryables are translated to VALUES, no need for JSON. // Column queryables have their type mapping from the model, so we don't ever need to apply an inferred mapping on them. if (openJsonExpression.JsonExpression is not SqlParameterExpression { TypeMapping: null } parameterExpression) @@ -77,15 +71,37 @@ protected virtual SqlServerOpenJsonExpression ApplyTypeMappingsOnOpenJsonExpress Check.DebugAssert( openJsonExpression.ColumnInfos is null, "OpenJsonExpression has no ColumnInfos when applying an inferred type mapping"); - // We need to apply the inferred type mapping in two places: the collection type mapping on the parameter expanded by OPENJSON, - // and on the WITH clause determining the conversion out on the SQL Server side + // In the usual case, some operation performed against the elements of the collection (e.g. comparison to a column) provides us with + // an element type mapping; infer the collection's type mapping from that. + // NOTE: This assumes that the OPENJSON always returns only a single column, which is currently true but won't always be. + RelationalTypeMapping? parameterTypeMapping; + + if (TryGetInferredTypeMapping(openJsonExpression.Alias, "value", out var elementTypeMapping)) + { + // We need to apply the inferred type mapping in two places: the collection type mapping on the parameter expanded by OPENJSON, + // and on the WITH clause determining the conversion out on the SQL Server side + + // First, find the collection type mapping and apply it to the parameter + parameterTypeMapping = _typeMappingSource.FindMapping(parameterExpression.Type, _model, elementTypeMapping); + } + else + { + // We have no inferred type mapping for the element type. This means that there was nothing in the query done + // against the elements of the collection (e.g. comparison to a column), which tells us what type mapping it is. + // In normal circumstances, such an expression would get client-evaluated in the funceltizer (no reference to a + // column/database-side object), but with compiled queries the collection parameter gets preserved as-is. + // The only thing we can do is apply the default type mapping. + parameterTypeMapping = _typeMappingSource.FindMapping(parameterExpression.Type, QueryCompilationContext.Model); + + if (parameterTypeMapping is not { ElementTypeMapping: RelationalTypeMapping e }) + { + throw new UnreachableException("Default type mapping has no element type mapping"); + } + + elementTypeMapping = e; + } - // First, find the collection type mapping and apply it to the parameter - if (_typeMappingSource.FindMapping(parameterExpression.Type, _model, elementTypeMapping) is not SqlServerStringTypeMapping - { - ElementTypeMapping: not null - } - parameterTypeMapping) + if (parameterTypeMapping is not SqlServerStringTypeMapping { ElementTypeMapping: not null }) { throw new UnreachableException("A SqlServerStringTypeMapping collection type mapping could not be found"); } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs index 8c9614e01ea..379b7fd03d8 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs @@ -1738,6 +1738,20 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +@ids='[]' + +SELECT VALUE c +FROM root c +WHERE (ARRAY_LENGTH(@ids) > 0) +"""); + } + public override async Task Column_collection_in_subquery_Union_parameter_collection() { await base.Column_collection_in_subquery_Union_parameter_collection(); diff --git a/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs index ba7a79ab7cf..481f5fdbee8 100644 --- a/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs @@ -1384,6 +1384,16 @@ public virtual async Task Parameter_collection_in_subquery_Union_another_paramet _ = compiledQuery(context, ints1, ints2).ToList(); } + [ConditionalFact] // #37370 + public virtual async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + var func = EF.CompileAsyncQuery( + (PrimitiveCollectionsContext context, int[] ids) => context.Set().Where(e => ids.Any())); + + await using var context = Fixture.CreateContext(); + _ = await func(context, []).ToListAsync(); + } + [ConditionalFact] public virtual Task Column_collection_in_subquery_Union_parameter_collection() { diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs index 0c63d5646cb..e78970f806f 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQueryOldSqlServerTest.cs @@ -1401,6 +1401,23 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[NullableWrappedId], [p].[NullableWrappedIdWithNullableComparer], [p].[String], [p].[Strings], [p].[WrappedId] +FROM [PrimitiveCollectionsEntity] AS [p] +WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT NULL AS [Value] + WHERE 0 = 1 + ) AS [i]) +"""); + } + public override async Task Project_collection_of_ints_simple() { await base.Project_collection_of_ints_simple(); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs index 8316226faf5..44be52bab86 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServer160Test.cs @@ -2021,6 +2021,23 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[NullableWrappedId], [p].[NullableWrappedIdWithNullableComparer], [p].[String], [p].[Strings], [p].[WrappedId] +FROM [PrimitiveCollectionsEntity] AS [p] +WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT NULL AS [Value] + WHERE 0 = 1 + ) AS [i]) +"""); + } + public override async Task Column_collection_in_subquery_Union_parameter_collection() { await base.Column_collection_in_subquery_Union_parameter_collection(); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerJsonTypeTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerJsonTypeTest.cs index 675be39bdd8..7b2f7989584 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerJsonTypeTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerJsonTypeTest.cs @@ -2168,6 +2168,23 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[NullableWrappedId], [p].[NullableWrappedIdWithNullableComparer], [p].[String], [p].[Strings], [p].[WrappedId] +FROM [PrimitiveCollectionsEntity] AS [p] +WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT NULL AS [Value] + WHERE 0 = 1 + ) AS [i]) +"""); + } + public override async Task Column_collection_in_subquery_Union_parameter_collection() { await base.Column_collection_in_subquery_Union_parameter_collection(); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs index c5f08aa72bd..4be28124528 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/PrimitiveCollectionsQuerySqlServerTest.cs @@ -2044,6 +2044,23 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +SELECT [p].[Id], [p].[Bool], [p].[Bools], [p].[DateTime], [p].[DateTimes], [p].[Enum], [p].[Enums], [p].[Int], [p].[Ints], [p].[NullableInt], [p].[NullableInts], [p].[NullableString], [p].[NullableStrings], [p].[NullableWrappedId], [p].[NullableWrappedIdWithNullableComparer], [p].[String], [p].[Strings], [p].[WrappedId] +FROM [PrimitiveCollectionsEntity] AS [p] +WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT NULL AS [Value] + WHERE 0 = 1 + ) AS [i]) +"""); + } + public override async Task Column_collection_in_subquery_Union_parameter_collection() { await base.Column_collection_in_subquery_Union_parameter_collection(); diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs index 1c94be49766..9308ae4ccc4 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/PrimitiveCollectionsQuerySqliteTest.cs @@ -1862,6 +1862,23 @@ public override async Task Parameter_collection_in_subquery_Union_another_parame AssertSql(); } + public override async Task Compiled_query_with_uncorrelated_parameter_collection_expression() + { + await base.Compiled_query_with_uncorrelated_parameter_collection_expression(); + + AssertSql( + """ +SELECT "p"."Id", "p"."Bool", "p"."Bools", "p"."DateTime", "p"."DateTimes", "p"."Enum", "p"."Enums", "p"."Int", "p"."Ints", "p"."NullableInt", "p"."NullableInts", "p"."NullableString", "p"."NullableStrings", "p"."NullableWrappedId", "p"."NullableWrappedIdWithNullableComparer", "p"."String", "p"."Strings", "p"."WrappedId" +FROM "PrimitiveCollectionsEntity" AS "p" +WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT NULL AS "Value" + WHERE 0 + ) AS "i") +"""); + } + public override async Task Parameter_collection_in_subquery_Union_column_collection_as_compiled_query() { await base.Parameter_collection_in_subquery_Union_column_collection_as_compiled_query();