Skip to content

Commit f1941f9

Browse files
authored
Merge branch 'release/10.0' into release/11.0
2 parents 869b844 + 73ad1d5 commit f1941f9

8 files changed

Lines changed: 138 additions & 21 deletions

File tree

‎Directory.Packages.props‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
<PackageVersion Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" />
3131
<PackageVersion Include="Microsoft.DotNet.Build.Tasks.Templating" Version="$(MicrosoftDotNetBuildTasksTemplatingVersion)" />
3232
<!-- Azure SDK for .NET dependencies -->
33-
<PackageVersion Include="Microsoft.Azure.Cosmos" Version="3.63.4" />
33+
<PackageVersion Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
3434
<!-- SQL Server dependencies -->
3535
<PackageVersion Include="Microsoft.Data.SqlClient" Version="7.1.1" />
3636
<PackageVersion Include="Microsoft.SqlServer.Types" Version="170.1000.7" />

‎src/EFCore.Relational/Extensions/RelationalModelExtensions.cs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,14 @@ public static IRelationalModel GetRelationalModel(this IModel model)
7070
if (relationalModel == null)
7171
{
7272
var relationalModelFactory = (Func<IRelationalModel>?)model.FindRuntimeAnnotationValue(
73-
RelationalAnnotationNames.RelationalModelFactory)
74-
?? throw new InvalidOperationException(CoreStrings.ModelNotFinalized(nameof(GetRelationalModel)));
73+
RelationalAnnotationNames.RelationalModelFactory);
74+
if (relationalModelFactory == null)
75+
{
76+
// The factory is removed after the relational model is created, which could have happened on another thread
77+
return (IRelationalModel?)model.FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel)
78+
?? throw new InvalidOperationException(CoreStrings.ModelNotFinalized(nameof(GetRelationalModel)));
79+
}
80+
7581
lock (relationalModelFactory)
7682
{
7783
relationalModel = model.GetOrAddRuntimeAnnotationValue(

‎src/EFCore.SqlServer/Query/Internal/SqlServerJsonPostprocessor.cs‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
1717
/// * When the column type in the WITH clause is a SQL Server "CLR type" - these are incompatible with WITH (e.g. hierarchy id).
1818
/// 2. Rewrite JsonScalarExpression (JSON_VALUE()) to OPENJSON for when JSON_VALUE() isn't compatible with the type (e.g. binary data
1919
/// which needs to be base64-decoded).
20+
/// 3. Restore native json inputs to JSON operations when OPENJSON's WITH clause only supports nvarchar(max).
2021
/// </summary>
2122
/// <remarks>
2223
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -30,10 +31,15 @@ public sealed class SqlServerJsonPostprocessor(
3031
SqlAliasManager? sqlAliasManager)
3132
: ExpressionVisitor
3233
{
34+
private static readonly bool UseOldBehavior39277 =
35+
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue39277", out var enabled) && enabled;
36+
3337
private readonly List<OuterApplyExpression> _openjsonOuterAppliesToAdd = [];
3438
private readonly Dictionary<(string, string), ColumnInfo> _columnsToRewrite = [];
39+
private readonly HashSet<(string, string)> _jsonColumnsToCast = [];
3540

3641
private RelationalTypeMapping? _nvarcharMaxTypeMapping;
42+
private bool _supportsJsonTypeInOpenJson;
3743

3844
/// <summary>
3945
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -42,8 +48,19 @@ public sealed class SqlServerJsonPostprocessor(
4248
/// doing so can result in application failures when updating to a new Entity Framework Core release.
4349
/// </summary>
4450
public Expression Process(Expression expression)
51+
=> Process(expression, supportsJsonTypeInOpenJson: true);
52+
53+
/// <summary>
54+
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
55+
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
56+
/// any release. You should only use it directly in your code with extreme caution and knowing that
57+
/// doing so can result in application failures when updating to a new Entity Framework Core release.
58+
/// </summary>
59+
internal Expression Process(Expression expression, bool supportsJsonTypeInOpenJson)
4560
{
4661
_columnsToRewrite.Clear();
62+
_jsonColumnsToCast.Clear();
63+
_supportsJsonTypeInOpenJson = supportsJsonTypeInOpenJson;
4764

4865
return Visit(expression);
4966
}
@@ -74,6 +91,19 @@ protected override Expression VisitExtension(Expression expression)
7491
{
7592
var table = selectExpression.Tables[i];
7693

94+
if (!UseOldBehavior39277
95+
&& !_supportsJsonTypeInOpenJson
96+
&& table.UnwrapJoin() is SqlServerOpenJsonExpression { ColumnInfos: { } jsonColumnInfos } jsonTable)
97+
{
98+
foreach (var columnInfo in jsonColumnInfos)
99+
{
100+
if (columnInfo is { AsJson: true, TypeMapping.StoreType: "json" })
101+
{
102+
_jsonColumnsToCast.Add((jsonTable.Alias, columnInfo.Name));
103+
}
104+
}
105+
}
106+
77107
if (table.UnwrapJoin() is SqlServerOpenJsonExpression { ColumnInfos: { } columnInfos } openJsonExpression
78108
// Condition 1: an ordering/projection still refers to the OPENJSON's [key] column - it needs to be preserved.
79109
&& (selectExpression.Orderings.Select(o => o.Expression)
@@ -172,6 +202,19 @@ protected override Expression VisitExtension(Expression expression)
172202
_openjsonOuterAppliesToAdd.Clear();
173203
}
174204

205+
if (!_supportsJsonTypeInOpenJson
206+
&& result.Alias is { } selectAlias)
207+
{
208+
foreach (var projection in result.Projection)
209+
{
210+
if (projection.Expression is ColumnExpression column
211+
&& _jsonColumnsToCast.Contains((column.TableAlias, column.Name)))
212+
{
213+
_jsonColumnsToCast.Add((selectAlias, projection.Alias));
214+
}
215+
}
216+
}
217+
175218
return result;
176219
}
177220

@@ -252,6 +295,23 @@ when _columnsToRewrite.TryGetValue((columnExpression.TableAlias, columnExpressio
252295
jsonScalar.IsNullable);
253296
}
254297

298+
case JsonScalarExpression
299+
{
300+
Json: ColumnExpression { TypeMapping: { StoreType: "json" } jsonTypeMapping } columnExpression,
301+
Path.Count: > 0
302+
} jsonScalar
303+
when jsonScalar.TypeMapping is not SqlServerStructuralJsonTypeMapping
304+
&& jsonScalar.TypeMapping?.ElementTypeMapping is null
305+
&& _jsonColumnsToCast.Contains((columnExpression.TableAlias, columnExpression.Name)):
306+
{
307+
var visited = (JsonScalarExpression)base.Visit(jsonScalar);
308+
309+
return visited.Update(sqlExpressionFactory.Convert(
310+
columnExpression.ApplyTypeMapping(jsonTypeMapping.WithStoreTypeAndSize("nvarchar(max)", null)),
311+
columnExpression.Type,
312+
jsonTypeMapping));
313+
}
314+
255315
// The SQL Server json type cannot be compared ("The JSON data type cannot be compared or sorted, except when using the
256316
// IS NULL operator"). So we find comparisons that involve the json type, and apply a conversion to string (nvarchar(max))
257317
// to both sides. We exempt this when one of the sides is a constant null (not required).

‎src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ public class SqlServerQuerySqlGenerator(
2323
ISqlServerSingletonOptions sqlServerSingletonOptions)
2424
: QuerySqlGenerator(dependencies)
2525
{
26+
private static readonly bool UseOldBehavior38615 =
27+
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue38615", out var enabled) && enabled;
28+
2629
private readonly IRelationalTypeMappingSource _typeMappingSource = typeMappingSource;
2730
private readonly ISqlGenerationHelper _sqlGenerationHelper = dependencies.SqlGenerationHelper;
2831
private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions = sqlServerSingletonOptions;
@@ -965,7 +968,8 @@ void GenerateColumnInfo(SqlServerOpenJsonExpression.ColumnInfo columnInfo)
965968
// OPENJSON() WITH clause AS JSON option requires nvarchar(max) on platforms that don't support the json data
966969
// type in OPENJSON (i.e. Azure SQL). SQL Server 2025 (17.x) added native support for json in OPENJSON WITH.
967970
// See: https://learn.microsoft.com/sql/t-sql/data-types/json-data-type#limitations
968-
if (columnInfo.AsJson
971+
if (!UseOldBehavior38615
972+
&& columnInfo.AsJson
969973
&& columnInfo.TypeMapping.StoreType == "json"
970974
&& (_sqlServerSingletonOptions.EngineType != SqlServerEngineType.SqlServer
971975
|| _sqlServerSingletonOptions.SqlServerCompatibilityLevel < 170))

‎src/EFCore.SqlServer/Query/Internal/SqlServerQueryTranslationPostprocessor.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
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.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
5+
using Microsoft.EntityFrameworkCore.SqlServer.Internal;
6+
47
namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
58

69
/// <summary>
@@ -22,6 +25,9 @@ public class SqlServerQueryTranslationPostprocessor(
2225

2326
private readonly SqlServerAggregateArgumentPostprocessor _aggregatePostprocessor = new(queryCompilationContext.SqlAliasManager);
2427
private readonly SqlServerSqlTreePruner _pruner = new();
28+
private readonly bool _supportsJsonTypeInOpenJson =
29+
queryCompilationContext.ContextOptions.FindExtension<SqlServerOptionsExtension>()! is
30+
{ EngineType: SqlServerEngineType.SqlServer, SqlServerCompatibilityLevel: >= 170 };
2531

2632
/// <summary>
2733
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -33,7 +39,7 @@ public override Expression Process(Expression query)
3339
{
3440
var query1 = base.Process(query);
3541

36-
var query2 = _jsonPostprocessor.Process(query1);
42+
var query2 = _jsonPostprocessor.Process(query1, _supportsJsonTypeInOpenJson);
3743
var query3 = _aggregatePostprocessor.Visit(query2);
3844

3945
new SqlServerVectorSearchWithoutApproximateDetector(queryCompilationContext).Visit(query3);

‎test/Directory.Packages.props‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="$(MicrosoftCodeAnalysisCSharpTestingVersion)" />
99
<PackageVersion Include="Azure.Identity" Version="$(AzureIdentityVersion)" />
1010
<PackageVersion Include="Azure.ResourceManager.CosmosDB" Version="$(AzureResourceManagerCosmosDBVersion)" />
11-
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.22" />
11+
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.23" />
1212
<PackageVersion Include="Microsoft.AspNetCore.OData" Version="9.5.0" />
1313
<PackageVersion Include="Microsoft.Data.SqlClient.Extensions.Azure" Version="7.1.1" />
1414
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="$(MicrosoftExtensionsConfigurationVersion)" />

‎test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ public void GetRelationalModel_throws_if_convention_has_not_run()
3535
public void ToReferentialAction_maps_DeleteBehavior_correctly(DeleteBehavior deleteBehavior, ReferentialAction expected)
3636
=> Assert.Equal(expected, RelationalModel.ToReferentialAction(deleteBehavior));
3737

38+
[Fact]
39+
public void GetRelationalModel_does_not_throw_if_relational_model_is_created_concurrently()
40+
{
41+
var model = new ConcurrentlyInitializedModel();
42+
var relationalModel = new RelationalModel(model);
43+
model.AddRuntimeAnnotation(
44+
RelationalAnnotationNames.RelationalModelFactory, (Func<IRelationalModel>)(() => relationalModel));
45+
46+
Assert.Same(relationalModel, model.GetRelationalModel());
47+
}
48+
3849
[Fact]
3950
public void Both_design_and_runtime_RelationalModels_are_built_for_external_model()
4051
{
@@ -4007,6 +4018,26 @@ protected virtual TestHelpers.TestModelBuilder CreateConventionModelBuilder()
40074018
public static void AssertEqual(IRelationalModel expectedModel, IRelationalModel actualModel)
40084019
=> RelationalModelAsserter.Instance.AssertEqual(expectedModel, actualModel);
40094020

4021+
private class ConcurrentlyInitializedModel() : RuntimeModel(skipDetectChanges: false, modelId: Guid.Empty, entityTypeCount: 0)
4022+
{
4023+
private bool _concurrentCallMade;
4024+
4025+
public override Annotation? FindRuntimeAnnotation(string name)
4026+
{
4027+
var annotation = base.FindRuntimeAnnotation(name);
4028+
if (name == RelationalAnnotationNames.RelationalModel
4029+
&& annotation == null
4030+
&& !_concurrentCallMade)
4031+
{
4032+
// Simulates another thread creating the relational model right after this lookup didn't find it
4033+
_concurrentCallMade = true;
4034+
this.GetRelationalModel();
4035+
}
4036+
4037+
return annotation;
4038+
}
4039+
}
4040+
40104041
public enum Mapping
40114042
{
40124043
TPH,

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

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
using Microsoft.Data.SqlClient;
55
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
66
using Microsoft.EntityFrameworkCore.SqlServer.Diagnostics.Internal;
7+
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
8+
using Microsoft.EntityFrameworkCore.SqlServer.Internal;
79
using Microsoft.EntityFrameworkCore.TestModels.JsonQuery;
810
using Xunit.Sdk;
911

@@ -1133,33 +1135,41 @@ public override async Task Json_collection_Any_with_predicate(bool async)
11331135
{
11341136
await base.Json_collection_Any_with_predicate(async);
11351137

1136-
// On Azure SQL, the json data type is not supported in the OPENJSON WITH clause, so nvarchar(max) is used instead.
1137-
if (SqlServerTestEnvironment.IsAzureSql)
1138-
{
1139-
AssertSql(
1140-
"""
1138+
using var context = Fixture.CreateContext();
1139+
1140+
AssertSql(
1141+
context.GetService<ISqlServerSingletonOptions>() is
1142+
{ EngineType: SqlServerEngineType.SqlServer, SqlServerCompatibilityLevel: >= 170 }
1143+
? """
11411144
SELECT [j].[Id], [j].[EntityBasicId], [j].[Name], [j].[OwnedCollectionRoot], [j].[OwnedReferenceRoot]
11421145
FROM [JsonEntitiesBasic] AS [j]
11431146
WHERE EXISTS (
11441147
SELECT 1
1145-
FROM OPENJSON([j].[OwnedReferenceRoot], '$.OwnedCollectionBranch') WITH ([OwnedReferenceLeaf] nvarchar(max) '$.OwnedReferenceLeaf' AS JSON) AS [o]
1148+
FROM OPENJSON([j].[OwnedReferenceRoot], '$.OwnedCollectionBranch') WITH ([OwnedReferenceLeaf] json '$.OwnedReferenceLeaf' AS JSON) AS [o]
11461149
WHERE JSON_VALUE([o].[OwnedReferenceLeaf], '$.SomethingSomething' RETURNING nvarchar(max)) = N'e1_r_c1_r')
1147-
""");
1148-
}
1149-
else
1150-
{
1151-
AssertSql(
1152-
"""
1150+
"""
1151+
: """
11531152
SELECT [j].[Id], [j].[EntityBasicId], [j].[Name], [j].[OwnedCollectionRoot], [j].[OwnedReferenceRoot]
11541153
FROM [JsonEntitiesBasic] AS [j]
11551154
WHERE EXISTS (
11561155
SELECT 1
1157-
FROM OPENJSON([j].[OwnedReferenceRoot], '$.OwnedCollectionBranch') WITH ([OwnedReferenceLeaf] json '$.OwnedReferenceLeaf' AS JSON) AS [o]
1158-
WHERE JSON_VALUE([o].[OwnedReferenceLeaf], '$.SomethingSomething' RETURNING nvarchar(max)) = N'e1_r_c1_r')
1156+
FROM OPENJSON([j].[OwnedReferenceRoot], '$.OwnedCollectionBranch') WITH ([OwnedReferenceLeaf] nvarchar(max) '$.OwnedReferenceLeaf' AS JSON) AS [o]
1157+
WHERE JSON_VALUE(CAST([o].[OwnedReferenceLeaf] AS json), '$.SomethingSomething' RETURNING nvarchar(max)) = N'e1_r_c1_r')
11591158
""");
1160-
}
11611159
}
11621160

1161+
[Theory, MemberData(nameof(IsAsyncData))]
1162+
public Task Json_collection_Any_with_nested_scalar_predicate(bool async)
1163+
=> AssertQuery(
1164+
async,
1165+
ss => ss.Set<JsonEntityBasic>().Where(e =>
1166+
e.OwnedReferenceRoot.OwnedCollectionBranch
1167+
.OrderBy(b => b.Date)
1168+
.Take(1)
1169+
.Any(b => b.OwnedReferenceLeaf.SomethingSomething!.ToLower().Contains("e1_r_c1")
1170+
&& b.Enum == JsonEnum.Two))
1171+
.Select(e => e.Id));
1172+
11631173
public override async Task Json_collection_Where_ElementAt(bool async)
11641174
{
11651175
await base.Json_collection_Where_ElementAt(async);

0 commit comments

Comments
 (0)