diff --git a/src/EFCore.Cosmos/Extensions/Internal/CosmosPropertyExtensions.cs b/src/EFCore.Cosmos/Extensions/Internal/CosmosPropertyExtensions.cs
index ce235b84b1d..fedd28e6825 100644
--- a/src/EFCore.Cosmos/Extensions/Internal/CosmosPropertyExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/Internal/CosmosPropertyExtensions.cs
@@ -1,6 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore.Cosmos.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Internal;
+
namespace Microsoft.EntityFrameworkCore.Cosmos.Extensions.Internal;
///
@@ -19,4 +23,29 @@ public static class CosmosPropertyExtensions
///
public static bool IsPersisted(this IReadOnlyProperty property)
=> property.GetJsonPropertyName() != string.Empty;
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public static string SerializeJsonId(this IProperty property, object? providerValue)
+ {
+ var mapping = property.GetTypeMapping();
+ var readerWriter = mapping.JsonValueReaderWriter!;
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ if (mapping.Converter is not null
+ && readerWriter is IJsonConvertedValueReaderWriter converted)
+ {
+ readerWriter = converted.InnerReaderWriter;
+ }
+#pragma warning restore EF1001
+
+ using var document = JsonDocument.Parse(readerWriter.ToJsonString(providerValue));
+ return document.RootElement.ValueKind == JsonValueKind.String
+ && document.RootElement.GetString() is { Length: > 0 } id
+ ? id
+ : throw new InvalidOperationException(CosmosStrings.InvalidResourceId);
+ }
}
diff --git a/src/EFCore.Cosmos/Extensions/Internal/PartitionKeyBuilderExtensions.cs b/src/EFCore.Cosmos/Extensions/Internal/PartitionKeyBuilderExtensions.cs
index c75555c02c2..4cfadeaff0a 100644
--- a/src/EFCore.Cosmos/Extensions/Internal/PartitionKeyBuilderExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/Internal/PartitionKeyBuilderExtensions.cs
@@ -1,7 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Globalization;
+using System.Text.Json;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Internal;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Internal;
@@ -32,66 +35,82 @@ public static PartitionKeyBuilder Add(this PartitionKeyBuilder builder, object?
: value;
}
- var converter = property?.GetTypeMapping().Converter;
+ var mapping = property?.GetTypeMapping();
+ var converter = mapping?.Converter;
+ var writeNull = value is not null || mapping?.JsonValueReaderWriter?.HandlesNullWrites == true;
if (converter != null)
{
value = converter.ConvertToProvider(value);
}
- if (value == null)
+ if (value != null)
{
- builder.AddNullValue();
- }
- else
- {
- var expectedType = (converter?.ProviderClrType ?? property?.ClrType)?.UnwrapNullableType();
- switch (value)
+ var valueType = value.GetType();
+ if (value is not string and not bool && !valueType.IsNumeric())
{
- case string stringValue:
- if (expectedType != null && expectedType != typeof(string))
- {
- CheckType(typeof(string));
- }
-
- builder.Add(stringValue);
- break;
-
- case bool boolValue:
- if (expectedType != null && expectedType != typeof(bool))
- {
- CheckType(typeof(bool));
- }
-
- builder.Add(boolValue);
- break;
-
- case var _ when value.GetType().IsNumeric():
- if (expectedType != null && !expectedType.IsNumeric())
- {
- CheckType(value.GetType());
- }
-
- builder.Add(Convert.ToDouble(value));
- break;
+ throw new InvalidOperationException(CosmosStrings.PartitionKeyBadValue(valueType));
+ }
- default:
- throw new InvalidOperationException(CosmosStrings.PartitionKeyBadValue(value.GetType()));
+ var expectedType = (converter?.ProviderClrType ?? property?.ClrType)?.UnwrapNullableType();
+ if (expectedType != null
+ && expectedType != valueType
+ && !(expectedType.IsNumeric() && valueType.IsNumeric()))
+ {
+ throw new InvalidOperationException(
+ CosmosStrings.PartitionKeyBadValueType(
+ expectedType.ShortDisplayName(),
+ property!.DeclaringType.DisplayName(),
+ property.Name,
+ valueType.DisplayName()));
}
+ }
+
+ var readerWriter = mapping?.JsonValueReaderWriter;
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ if (converter is not null
+ && readerWriter is IJsonConvertedValueReaderWriter converted)
+ {
+ readerWriter = converted.InnerReaderWriter;
+ }
+#pragma warning restore EF1001
- void CheckType(Type actualType)
+ if (readerWriter != null
+ && writeNull
+ && (value != null || readerWriter.HandlesNullWrites))
+ {
+ if (value != null
+ && !readerWriter.ValueType.IsInstanceOfType(value)
+ && value.GetType().IsNumeric()
+ && readerWriter.ValueType.IsNumeric())
{
- if (expectedType != null && expectedType != actualType)
+ // Unconfigured numeric keys must not be narrowed to the property's CLR type.
+ if (property!.GetJsonValueReaderWriter() == null
+ && property.DeclaringType.Model.FindTypeMappingConfiguration(property.ClrType.UnwrapNullableType())
+ ?.GetJsonValueReaderWriterType() == null)
{
- throw new InvalidOperationException(
- CosmosStrings.PartitionKeyBadValueType(
- expectedType.ShortDisplayName(),
- property!.DeclaringType.DisplayName(),
- property.Name,
- actualType.DisplayName()));
+ return builder.Add(Convert.ToDouble(value));
}
+
+ value = Convert.ChangeType(value, readerWriter.ValueType, CultureInfo.InvariantCulture);
}
+
+ using var document = JsonDocument.Parse(readerWriter.ToJsonString(value));
+ value = document.RootElement.ValueKind switch
+ {
+ JsonValueKind.Null => null,
+ JsonValueKind.String => document.RootElement.GetString(),
+ JsonValueKind.True or JsonValueKind.False => document.RootElement.GetBoolean(),
+ JsonValueKind.Number => document.RootElement.GetDouble(),
+ _ => throw new InvalidOperationException(CosmosStrings.PartitionKeyBadValue(typeof(JsonElement)))
+ };
}
- return builder;
+ return value switch
+ {
+ null => builder.AddNullValue(),
+ string stringValue => builder.Add(stringValue),
+ bool boolValue => builder.Add(boolValue),
+ _ => builder.Add(Convert.ToDouble(value))
+ };
}
}
diff --git a/src/EFCore.Cosmos/Infrastructure/Internal/CosmosModelValidator.cs b/src/EFCore.Cosmos/Infrastructure/Internal/CosmosModelValidator.cs
index 7469545379d..46282300844 100644
--- a/src/EFCore.Cosmos/Infrastructure/Internal/CosmosModelValidator.cs
+++ b/src/EFCore.Cosmos/Infrastructure/Internal/CosmosModelValidator.cs
@@ -16,6 +16,10 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.Infrastructure.Internal;
///
public class CosmosModelValidator(ModelValidatorDependencies dependencies) : ModelValidator(dependencies)
{
+ ///
+ protected override bool IsJsonProperty(IProperty property)
+ => property.IsPersisted();
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
index 3ef7e933414..8b6c3255fe9 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
@@ -23,10 +23,10 @@ public class CosmosQuerySqlGenerator(ITypeMappingSource typeMappingSource, IMode
private List _sqlParameters = null!;
///
- /// Lookup table from (the "original" name) to the Cosmos ,
- /// whose name has underdone uniquification and prefixing. This is used when the same parameter is referenced multiple times in the query.
+ /// Lookup table from the original parameter name and type mapping to the Cosmos ,
+ /// whose name has undergone uniquification and prefixing. This is used when the same parameter is referenced multiple times in the query.
///
- private Dictionary _sqlParametersByOriginalName = null!;
+ private Dictionary<(string, CoreTypeMapping), SqlParameter> _sqlParametersByOriginalName = null!;
///
/// Contains final parameter names (prefixed, uniquified) seen so far, for uniquification purposes.
@@ -815,18 +815,19 @@ protected virtual Expression VisitCase(CaseExpression caseExpression)
///
protected virtual Expression VisitSqlParameter(SqlParameterExpression sqlParameterExpression)
{
- if (!_sqlParametersByOriginalName.TryGetValue(sqlParameterExpression.Name, out var sqlParameter))
- {
- Check.DebugAssert(sqlParameterExpression.TypeMapping is not null, "SqlParameterExpression without a type mapping.");
+ Check.DebugAssert(sqlParameterExpression.TypeMapping is not null, "SqlParameterExpression without a type mapping.");
+ var typeMapping = (CosmosTypeMapping)sqlParameterExpression.TypeMapping;
+ var key = (sqlParameterExpression.Name, typeMapping);
+ if (!_sqlParametersByOriginalName.TryGetValue(key, out var sqlParameter))
+ {
var parameterName = PrefixAndUniquifyParameterName(sqlParameterExpression.Name);
var value = _parameterValues[sqlParameterExpression.Name];
- sqlParameter = ((CosmosTypeMapping)sqlParameterExpression.TypeMapping)
- .CreateParameter(parameterName, value);
+ sqlParameter = typeMapping.CreateParameter(parameterName, value);
- _sqlParametersByOriginalName[sqlParameterExpression.Name] = sqlParameter;
+ _sqlParametersByOriginalName[key] = sqlParameter;
_sqlParameters.Add(sqlParameter);
}
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
index 5e085ced38a..924c1547697 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
@@ -18,6 +18,7 @@ public class CosmosQueryableMethodTranslatingExpressionVisitor : QueryableMethod
private readonly CosmosQueryCompilationContext _queryCompilationContext;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly ITypeMappingSource _typeMappingSource;
+ private readonly CoreTypeMapping _intTypeMapping;
private readonly IMemberTranslatorProvider _memberTranslatorProvider;
private readonly IMethodCallTranslatorProvider _methodCallTranslatorProvider;
private readonly ICosmosStructuralTypeSerializerProvider _structuralTypeSerializerProvider;
@@ -45,6 +46,7 @@ public CosmosQueryableMethodTranslatingExpressionVisitor(
_queryCompilationContext = queryCompilationContext;
_sqlExpressionFactory = sqlExpressionFactory;
_typeMappingSource = typeMappingSource;
+ _intTypeMapping = typeMappingSource.FindMapping(typeof(int))!;
_memberTranslatorProvider = memberTranslatorProvider;
_methodCallTranslatorProvider = methodCallTranslatorProvider;
_structuralTypeSerializerProvider = structuralTypeSerializerProvider;
@@ -75,6 +77,7 @@ protected CosmosQueryableMethodTranslatingExpressionVisitor(
_queryCompilationContext = parentVisitor._queryCompilationContext;
_sqlExpressionFactory = parentVisitor._sqlExpressionFactory;
_typeMappingSource = parentVisitor._typeMappingSource;
+ _intTypeMapping = parentVisitor._intTypeMapping;
_memberTranslatorProvider = parentVisitor._memberTranslatorProvider;
_methodCallTranslatorProvider = parentVisitor._methodCallTranslatorProvider;
_structuralTypeSerializerProvider = parentVisitor._structuralTypeSerializerProvider;
@@ -465,7 +468,7 @@ private ShapedQueryExpression CreateShapedQueryExpression(SelectExpression selec
var projectionMapping = new Dictionary { { new ProjectionMember(), topLevelTranslation } };
subquery.ReplaceProjectionMapping(projectionMapping);
- return !TryApplyLimit(subquery, TranslateExpression(Expression.Constant(1))!)
+ return !TryApplyLimit(subquery, _sqlExpressionFactory.Constant(1, _intTypeMapping))
? null
: source
.UpdateShaperExpression(
@@ -523,7 +526,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
// Simplify x.Array.Contains[1] => ARRAY_CONTAINS(x.Array, 1) insert of IN+subquery
if (source.TryExtractArray(out var array, ignoreOrderings: true)
&& array is SqlExpression scalarArray // TODO: Contains over arrays of structural types, #34027
- && TranslateExpression(item) is { } translatedItem)
+ && TranslateExpression(item, scalarArray.TypeMapping?.ElementTypeMapping) is { } translatedItem)
{
if (array is ArrayConstantExpression arrayConstant)
{
@@ -595,7 +598,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
Expression index,
bool returnDefault)
{
- if (TranslateExpression(index) is not { } translatedIndex)
+ if (TranslateExpression(index, _intTypeMapping) is not { } translatedIndex)
{
return null;
}
@@ -681,7 +684,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
}
if (!TryApplyOffset(select, translatedIndex)
- || !TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!))
+ || !TryApplyLimit(select, _sqlExpressionFactory.Constant(1, _intTypeMapping)))
{
return null;
}
@@ -734,7 +737,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
var select = (SelectExpression)source.QueryExpression;
- if (!TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!))
+ if (!TryApplyLimit(select, _sqlExpressionFactory.Constant(1, _intTypeMapping)))
{
return null;
}
@@ -827,7 +830,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
var select = (SelectExpression)source.QueryExpression;
select.ReverseOrderings();
- return !TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!)
+ return !TryApplyLimit(select, _sqlExpressionFactory.Constant(1, _intTypeMapping))
? null
: source.ShaperExpression.Type != returnType
? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, returnType))
@@ -1137,7 +1140,7 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
}
var select = (SelectExpression)source.QueryExpression;
- return !TryApplyLimit(select, TranslateExpression(Expression.Constant(2))!)
+ return !TryApplyLimit(select, _sqlExpressionFactory.Constant(2, _intTypeMapping))
? null
: source.ShaperExpression.Type == returnType
? source
@@ -1152,7 +1155,7 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
///
protected override ShapedQueryExpression? TranslateSkip(ShapedQueryExpression source, Expression count)
{
- if (TranslateExpression(count) is not { } translatedCount)
+ if (TranslateExpression(count, _intTypeMapping) is not { } translatedCount)
{
return null;
}
@@ -1258,7 +1261,7 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
///
protected override ShapedQueryExpression? TranslateTake(ShapedQueryExpression source, Expression count)
{
- if (TranslateExpression(count) is not { } translatedCount)
+ if (TranslateExpression(count, _intTypeMapping) is not { } translatedCount)
{
return null;
}
@@ -1287,7 +1290,7 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
} previousSlice
? previousSlice.Update([nestedArray, skipCount, translatedCount])
: _sqlExpressionFactory.Function(
- "ARRAY_SLICE", [scalarArray, TranslateExpression(Expression.Constant(0))!, translatedCount], scalarArray.Type,
+ "ARRAY_SLICE", [scalarArray, _sqlExpressionFactory.Constant(0, _intTypeMapping), translatedCount], scalarArray.Type,
scalarArray.TypeMapping);
var alias = _aliasManager.GenerateSourceAlias(slice);
@@ -1308,7 +1311,7 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
} previousSlice
? previousSlice.Update([nestedArray, skipCount, translatedCount])
: new ObjectFunctionExpression(
- "ARRAY_SLICE", [array, TranslateExpression(Expression.Constant(0))!, translatedCount],
+ "ARRAY_SLICE", [array, _sqlExpressionFactory.Constant(0, _intTypeMapping), translatedCount],
projectedStructuralTypeShaper.Type);
var alias = _aliasManager.GenerateSourceAlias(slice);
@@ -1479,11 +1482,12 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
translatedItems[i] = translatedItem;
}
- // TODO: Temporary hack - need to perform proper derivation of the array type mapping from the element (e.g. for
- // value conversion). #34026.
+ // TODO: Infer a common element mapping when inline items use different conversions. #34026.
var elementClrType = inlineQueryRootExpression.ElementType;
- var elementTypeMapping = _typeMappingSource.FindMapping(elementClrType)!;
- var arrayTypeMapping = _typeMappingSource.FindMapping(typeof(IEnumerable<>).MakeGenericType(elementClrType));
+ var elementTypeMapping = translatedItems.FirstOrDefault()?.TypeMapping
+ ?? _typeMappingSource.FindMapping(elementClrType, _queryCompilationContext.Model)!;
+ var arrayTypeMapping = _typeMappingSource.FindMapping(
+ typeof(IEnumerable<>).MakeGenericType(elementClrType), _queryCompilationContext.Model, elementTypeMapping);
var inlineArray = new ArrayConstantExpression(elementClrType, translatedItems, arrayTypeMapping);
var sourceAlias = _aliasManager.GenerateSourceAlias(inlineArray);
@@ -1504,11 +1508,10 @@ private static Expression UnwrapInclude(IncludeExpression includeExpression)
{
var queryParameter = parameterQueryRootExpression.QueryParameterExpression;
- // TODO: Temporary hack - need to perform proper derivation of the array type mapping from the element (e.g. for
- // value conversion). #34026.
var elementClrType = parameterQueryRootExpression.ElementType;
- var arrayTypeMapping = _typeMappingSource.FindMapping(typeof(IEnumerable<>).MakeGenericType(elementClrType));
- var elementTypeMapping = _typeMappingSource.FindMapping(elementClrType)!;
+ var elementTypeMapping = _typeMappingSource.FindMapping(elementClrType, _queryCompilationContext.Model)!;
+ var arrayTypeMapping = _typeMappingSource.FindMapping(
+ typeof(IEnumerable<>).MakeGenericType(elementClrType), _queryCompilationContext.Model, elementTypeMapping);
var sqlParameterExpression = new SqlParameterExpression(queryParameter.Name, queryParameter.Type, arrayTypeMapping);
var sourceAlias = _aliasManager.GenerateSourceAlias(sqlParameterExpression.Name.TrimStart('_'));
@@ -1685,8 +1688,8 @@ private bool TryPushdownIntoSubquery(SelectExpression select)
source = translatedSource;
}
- var translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(
- _sqlExpressionFactory.Function("COUNT", [_sqlExpressionFactory.Constant(1)], typeof(int)));
+ var translation = _sqlExpressionFactory.Function(
+ "COUNT", [_sqlExpressionFactory.Constant(1, _intTypeMapping)], typeof(int), _intTypeMapping);
var projectionMapping = new Dictionary { { new ProjectionMember(), translation } };
@@ -1758,9 +1761,11 @@ static bool IsRootEntityQuery(ShapedQueryExpression source)
=> source.QueryExpression is SelectExpression { Sources: [{ WithIn: false }, ..] };
}
- private SqlExpression? TranslateExpression(Expression expression)
+ private SqlExpression? TranslateExpression(Expression expression, CoreTypeMapping? typeMapping = null)
{
- var translation = _sqlTranslator.Translate(expression);
+ var translation = typeMapping is null
+ ? _sqlTranslator.Translate(expression)
+ : _sqlTranslator.Translate(expression, typeMapping);
if (translation == null && _sqlTranslator.TranslationErrorDetails != null)
{
AddTranslationErrorDetails(_sqlTranslator.TranslationErrorDetails);
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs
index 759eac3f78d..3f3cb1707d0 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
+using Microsoft.EntityFrameworkCore.Cosmos.Extensions.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal;
@@ -89,7 +90,15 @@ private bool TryGetResourceId(out string resourceId)
}
resourceId = jsonIdDefinition.GenerateIdString(values);
- return string.IsNullOrEmpty(resourceId) ? throw new InvalidOperationException(CosmosStrings.InvalidResourceId) : true;
+ if (string.IsNullOrEmpty(resourceId))
+ {
+ throw new InvalidOperationException(CosmosStrings.InvalidResourceId);
+ }
+
+ var idProperty = _rootEntityType.GetProperties()
+ .Single(p => p.GetJsonPropertyName() == CosmosJsonIdConvention.IdPropertyJsonName);
+ resourceId = idProperty.SerializeJsonId(resourceId);
+ return true;
}
private sealed class AsyncEnumerator : IAsyncEnumerator
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
index 16a36c85550..3f5546ee8a6 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
@@ -447,7 +447,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp
if (IsValueBufferTryReadValueMethodCall(methodCallExpression, out var property))
{
var typeMapping = property.GetTypeMapping();
- var jsonValueReaderWriter = property.GetJsonValueReaderWriter() ?? typeMapping.JsonValueReaderWriter;
+ var jsonValueReaderWriter = typeMapping.JsonValueReaderWriter;
Debug.Assert(
jsonValueReaderWriter != null,
"JsonValueReaderWriter should not be null since we are in Cosmos provider and all types should have JsonValueReaderWriter");
@@ -859,7 +859,7 @@ private BlockExpression ReadDiscriminator(
discriminatorValueVariable,
ReadJsonValue(
_jsonReaderManagerVariable,
- discriminatorProperty.GetJsonValueReaderWriter() ?? typeMapping.JsonValueReaderWriter!,
+ typeMapping.JsonValueReaderWriter!,
typeMapping, discriminatorProperty.ClrType.MakeNullable(), true)),
// goto EndRead
Break(breakLabel, typeof(void))),
@@ -1102,7 +1102,7 @@ private BlockExpression RewriteStructuralTypeCase(BlockExpression body, ITypeBas
finalBlockVariables.Add(propertyVariable);
var typeMapping = property.GetTypeMapping();
- var jsonValueReaderWriter = property.GetJsonValueReaderWriter() ?? typeMapping.JsonValueReaderWriter;
+ var jsonValueReaderWriter = typeMapping.JsonValueReaderWriter;
Debug.Assert(
jsonValueReaderWriter != null,
"JsonValueReaderWriter should not be null since we are in Cosmos provider and all types should have JsonValueReaderWriter");
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
index e1b87deeb91..492efca9dc1 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
@@ -76,6 +76,13 @@ protected virtual void AddTranslationErrorDetails(string details)
return TranslateInternal(expression, applyDefaultTypeMapping) as SqlExpression;
}
+ internal SqlExpression? Translate(Expression expression, CoreTypeMapping typeMapping)
+ {
+ TranslationErrorDetails = null;
+
+ return TranslateInternal(expression, expectedTypeMapping: typeMapping) as SqlExpression;
+ }
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
@@ -103,7 +110,11 @@ protected virtual void AddTranslationErrorDetails(string details)
};
}
- private Expression? TranslateInternal(Expression expression, bool applyDefaultTypeMapping = true, bool isProjection = false)
+ private Expression? TranslateInternal(
+ Expression expression,
+ bool applyDefaultTypeMapping = true,
+ bool isProjection = false,
+ CoreTypeMapping? expectedTypeMapping = null)
{
var result = Visit(expression);
@@ -117,7 +128,9 @@ protected virtual void AddTranslationErrorDetails(string details)
if (applyDefaultTypeMapping)
{
- translation = sqlExpressionFactory.ApplyDefaultTypeMapping(translation);
+ translation = expectedTypeMapping is null
+ ? sqlExpressionFactory.ApplyDefaultTypeMapping(translation)
+ : sqlExpressionFactory.ApplyTypeMapping(translation, expectedTypeMapping);
if (translation.TypeMapping == null)
{
diff --git a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
index 6ed9e3e7297..4f5bb1ca702 100644
--- a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
+++ b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
@@ -16,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
public class SqlExpressionFactory(ITypeMappingSource typeMappingSource, IModel model)
: ISqlExpressionFactory
{
- private readonly CoreTypeMapping _boolTypeMapping = typeMappingSource.FindMapping(typeof(bool), model)!;
+ private readonly CoreTypeMapping _boolTypeMapping = typeMappingSource.FindMapping(typeof(bool))!;
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -28,7 +28,11 @@ public class SqlExpressionFactory(ITypeMappingSource typeMappingSource, IModel m
public virtual SqlExpression? ApplyDefaultTypeMapping(SqlExpression? sqlExpression)
=> sqlExpression is not { TypeMapping: null }
? sqlExpression
- : ApplyTypeMapping(sqlExpression, typeMappingSource.FindMapping(sqlExpression.Type, model));
+ : ApplyTypeMapping(
+ sqlExpression,
+ sqlExpression is SqlFunctionExpression && sqlExpression.Type.UnwrapNullableType() == typeof(bool)
+ ? _boolTypeMapping
+ : typeMappingSource.FindMapping(sqlExpression.Type, model));
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -165,6 +169,15 @@ private SqlExpression ApplyTypeMappingOnSqlBinary(
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
{
+ if (left is SqlConstantExpression && right is not SqlConstantExpression && right.TypeMapping is { } rightMapping)
+ {
+ left = SetTypeMapping(left, rightMapping);
+ }
+ else if (right is SqlConstantExpression && left is not SqlConstantExpression && left.TypeMapping is { } leftMapping)
+ {
+ right = SetTypeMapping(right, leftMapping);
+ }
+
inferredTypeMapping = ExpressionExtensions.InferTypeMapping(left, right)
// We avoid object here since the result does not get typeMapping from outside.
?? (left.Type != typeof(object)
@@ -286,13 +299,16 @@ private InExpression ApplyTypeMappingOnIn(InExpression inExpression)
case { Values: { } values }:
SqlExpression[]? newValues = null;
- if (missingTypeMappingInValues)
+ if (missingTypeMappingInValues
+ || values.Any(v => v is SqlConstantExpression && v.TypeMapping != item.TypeMapping))
{
newValues = new SqlExpression[values.Count];
for (var i = 0; i < newValues.Length; i++)
{
- newValues[i] = ApplyTypeMapping(values[i], item.TypeMapping);
+ newValues[i] = values[i] is SqlConstantExpression
+ ? SetTypeMapping(values[i], item.TypeMapping!)
+ : ApplyTypeMapping(values[i], item.TypeMapping);
}
}
@@ -334,8 +350,8 @@ private InExpression ApplyTypeMappingOnIn(InExpression inExpression)
throw new InvalidOperationException("Couldn't find element type mapping when applying item/array mappings");
}
- // If the array's type mapping isn't provided (parameter/constant), attempt to infer it from the item.
- if (arrayMapping is null)
+ // Parameters must use the compared member's element mapping, including its JSON formatter.
+ if (arrayMapping is null || arrayExpression is SqlParameterExpression)
{
// Get a type mapping for the array from the item.
// If the array CLR type is anything but an object[], just use that CLR type.
@@ -351,7 +367,7 @@ var t when t.TryGetSequenceType() != typeof(object) => t,
$"Can't construct generic primitive collection type for array type '{arrayExpression.Type}'")
};
- arrayMapping = typeMappingSource.FindMapping(arrayClrType, model, itemMapping.ElementTypeMapping);
+ arrayMapping = typeMappingSource.FindMapping(arrayClrType, model, itemMapping);
if (arrayMapping is null)
{
@@ -359,7 +375,7 @@ var t when t.TryGetSequenceType() != typeof(object) => t,
}
}
- return (ApplyTypeMapping(itemExpression, itemMapping), ApplyTypeMapping(arrayExpression, arrayMapping));
+ return (ApplyTypeMapping(itemExpression, itemMapping), SetTypeMapping(arrayExpression, arrayMapping));
}
///
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs
index 6a3d46e833b..0ad0558457d 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs
@@ -60,16 +60,14 @@ public CosmosStructuralTypeSerializer(ICosmosStructuralTypeSerializerProvider pr
_discriminatorProperty = structuralType.FindDiscriminatorProperty() is { } dp
? (dp, dp.GetJsonPropertyName(),
- dp.GetJsonValueReaderWriter()
- ?? dp.GetTypeMapping().JsonValueReaderWriter ?? throw new UnreachableException("Property without JsonValueReaderWriter"))
+ dp.GetTypeMapping().JsonValueReaderWriter ?? throw new UnreachableException("Property without JsonValueReaderWriter"))
: null;
_ordinalKeyProperty = structuralType.GetProperties().SingleOrDefault(p => p.IsOrdinalKeyProperty());
_scalarProperties =
[
.. structuralType.GetProperties().Where(p => p.IsPersisted() && p != _discriminatorProperty?.Property).Select(p
=> (p, p.GetJsonPropertyName(),
- p.GetJsonValueReaderWriter()
- ?? p.GetTypeMapping().JsonValueReaderWriter
+ p.GetTypeMapping().JsonValueReaderWriter
?? throw new UnreachableException("Property without JsonValueReaderWriter")))
];
_complexProperties =
@@ -113,8 +111,10 @@ public virtual string Container
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
public virtual string GetJsonId(IUpdateEntry entry)
- => (string)entry.GetCurrentProviderValue(
- _jsonIdProperty ?? throw new UnreachableException("Can not get json id for non root document type"))!;
+ {
+ var property = _jsonIdProperty ?? throw new UnreachableException("Can not get json id for non root document type");
+ return property.SerializeJsonId(entry.GetCurrentProviderValue(property));
+ }
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs
index 00d69edb435..f3d906a73c8 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs
@@ -102,20 +102,13 @@ public virtual SqlParameter CreateParameter(string name, object? value)
return TryCreateElementwiseParameter(name, normalized) ?? new SqlValueParameter(name, ConvertToProviderValue(value));
}
- using var stream = new MemoryStream();
- using (var writer = new Utf8JsonWriter(stream, CosmosClientWrapper.JsonWriterOptions))
- {
- if (normalized is not null || JsonValueReaderWriter!.HandlesNullWrites)
- {
- JsonValueReaderWriter!.ToJson(writer, normalized!);
- }
- else
- {
- writer.WriteNullValue();
- }
- }
-
- return new SqlRawJsonParameter(name, stream.ToArray());
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ return new SqlRawJsonParameter(
+ name,
+ normalized is null && !JsonValueReaderWriter!.HandlesNullWrites
+ ? "null"u8.ToArray()
+ : JsonValueReaderWriter!.ToJsonBytes(normalized, CosmosClientWrapper.JsonWriterOptions));
+#pragma warning restore EF1001
}
private SqlParameter? TryCreateElementwiseParameter(string name, object value)
@@ -136,18 +129,11 @@ public virtual SqlParameter CreateParameter(string name, object? value)
writer.WriteStartArray();
foreach (var element in elements)
{
- if (element is null)
+ if (element is null && !elementReaderWriter.HandlesNullWrites)
{
- if (elementReaderWriter.HandlesNullWrites)
- {
- elementReaderWriter.ToJson(writer, null);
- }
- else
- {
- writer.WriteNullValue();
- }
+ writer.WriteNullValue();
}
- else if (elementType.IsInstanceOfType(element))
+ else if (element is null || elementType.IsInstanceOfType(element))
{
elementReaderWriter.ToJson(writer, element);
}
@@ -190,21 +176,11 @@ public virtual SqlParameter CreateParameter(string name, object? value)
public virtual string GenerateSqlLiteral(object? value)
{
value = NormalizeValue(value);
+#pragma warning disable EF1001 // Internal EF Core API usage.
return value is not null || JsonValueReaderWriter!.HandlesNullWrites
- ? ToCosmosJsonString(value)
+ ? Encoding.UTF8.GetString(JsonValueReaderWriter!.ToJsonBytes(value, CosmosClientWrapper.JsonWriterOptions).Span)
: "null";
- }
-
- private string ToCosmosJsonString(object? value)
- {
- using var stream = new MemoryStream();
- using var writer = new Utf8JsonWriter(stream, CosmosClientWrapper.JsonWriterOptions);
-
- JsonValueReaderWriter!.ToJson(writer, value);
-
- writer.Flush();
-
- return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
+#pragma warning restore EF1001
}
private object? NormalizeValue(object? value)
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
index f2f24bf2a26..d6c24d4784a 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
@@ -53,6 +53,30 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
? CreateVectorTypeMapping(property, new CosmosVectorType(distanceFunction, dimensions))
: base.FindMapping(property);
+ ///
+ protected override CoreTypeMapping? FindElementMapping(TypeMappingInfo mappingInfo, IModel model)
+ {
+ var clrType = mappingInfo.ClrType!;
+ // Cosmos maps ReadOnlyMemory as a JSON array, although it does not implement IEnumerable.
+ if (clrType.TryGetElementType(typeof(ReadOnlyMemory<>)) is { } memoryType)
+ {
+ return FindMapping(memoryType, model);
+ }
+
+ // These are the dictionary shapes supported by FindCollectionMapping; JSON object keys must be strings.
+ if (clrType.IsGenericType
+ && clrType.GetGenericTypeDefinition() is var definition
+ && (definition == typeof(Dictionary<,>)
+ || definition == typeof(IDictionary<,>)
+ || definition == typeof(IReadOnlyDictionary<,>))
+ && clrType.GenericTypeArguments[0] == typeof(string))
+ {
+ return FindMapping(clrType.GenericTypeArguments[1], model);
+ }
+
+ return base.FindElementMapping(mappingInfo, model);
+ }
+
private CosmosVectorTypeMapping? CreateVectorTypeMapping(IProperty property, CosmosVectorType cosmosVectorType)
{
var clrType = property.ClrType;
@@ -64,10 +88,12 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
}
var sequenceType = collectionType.GetSequenceType();
- var elementMappingInfo = new TypeMappingInfo(sequenceType);
+ var mappingInfo = new TypeMappingInfo(property);
+ var elementMapping = property.GetElementType() is { } elementType
+ ? FindMapping(elementType)
+ : FindMapping(sequenceType, property.DeclaringType.Model);
- CoreTypeMapping? _ = null;
- if (!TryFindJsonCollectionMapping(elementMappingInfo, collectionType, null, ref _, out var _, out var readerWriter))
+ if (!TryFindJsonCollectionMapping(mappingInfo, collectionType, null, ref elementMapping, out _, out var readerWriter))
{
return null;
}
@@ -98,7 +124,11 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
? mapping
: (base.FindMapping(mappingInfo) // This will find a mapping from plugins, and so must happen first. See #34041.
?? FindPrimitiveMapping(mappingInfo)
- ?? FindCollectionMapping(mappingInfo));
+ ?? FindCollectionMapping(mappingInfo)
+ ?? (mappingInfo.JsonValueReaderWriter is { } readerWriter
+ && readerWriter.ValueType.IsAssignableFrom(clrType)
+ ? CreateMapping(clrType, jsonValueReaderWriter: readerWriter)
+ : null));
}
private CoreTypeMapping? FindPrimitiveMapping(in TypeMappingInfo mappingInfo)
@@ -108,12 +138,11 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
var memoryType = clrType.TryGetElementType(typeof(ReadOnlyMemory<>));
if (memoryType != null)
{
- var elementMappingInfo = new TypeMappingInfo(memoryType);
- CoreTypeMapping? typeMapping = null;
+ var typeMapping = mappingInfo.ElementTypeMapping;
return !TryFindJsonCollectionMapping(
- elementMappingInfo, memoryType.MakeArrayType(), null, ref typeMapping, out _, out var readerWriter)
+ mappingInfo, memoryType.MakeArrayType(), null, ref typeMapping, out _, out var readerWriter)
? null
- : CreateMapping(clrType, jsonValueReaderWriter: readerWriter)
+ : CreateMapping(clrType, elementMapping: typeMapping, jsonValueReaderWriter: readerWriter)
.WithComposedConverter(
(ValueConverter)Activator.CreateInstance(typeof(ReadOnlyMemoryConverter<>).MakeGenericType(memoryType))!,
(ValueComparer)Activator.CreateInstance(typeof(ReadOnlyMemoryComparer<>).MakeGenericType(memoryType))!);
@@ -161,10 +190,7 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
}
// Next, attempt to resolve this as a dictionary (e.g. Dictionary).
- if (elementMapping is not null)
- {
- return null;
- }
+ elementMapping = mappingInfo.ElementTypeMapping;
var elementType = clrType.TryGetSequenceType();
if (elementType == null)
@@ -190,7 +216,7 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
elementType = genericArguments[1];
var elementMappingInfo = new TypeMappingInfo(elementType);
- elementMapping = FindPrimitiveMapping(elementMappingInfo)
+ elementMapping ??= FindPrimitiveMapping(elementMappingInfo)
?? FindCollectionMapping(elementMappingInfo);
if (elementMapping != null)
@@ -202,7 +228,7 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
jsonValueReaderWriter = elementType.IsNullableValueType()
? (JsonValueReaderWriter?)Activator.CreateInstance(
typeof(CosmosJsonStringKeyedDictionaryNullableValueReaderWriter<>)
- .MakeGenericType(elementMapping.JsonValueReaderWriter.ValueType),
+ .MakeGenericType(elementType.UnwrapNullableType()),
elementMapping.JsonValueReaderWriter)
: elementType != typeof(string) && elementType.TryGetElementType(typeof(IEnumerable<>)) is { } nestedElementType
? nestedElementType.IsClass
@@ -401,7 +427,7 @@ public sealed class CosmosJsonStringKeyedDictionaryNullableValueReaderWriter _elementReaderWriter = (JsonValueReaderWriter)elementReaderWriter;
+ private readonly JsonValueReaderWriter _elementReaderWriter = elementReaderWriter;
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -433,7 +459,7 @@ public sealed class CosmosJsonStringKeyedDictionaryNullableValueReaderWriter
#pragma warning disable EF1001
- public sealed class CosmosJsonStringKeyedDictionaryCollectionValueReaderWriter(
+ public class CosmosJsonStringKeyedDictionaryCollectionValueReaderWriter(
JsonValueReaderWriter elementReaderWriter)
: JsonValueReaderWriter>>, ICompositeJsonValueReaderWriter
where TConcreteCollection : IEnumerable
#pragma warning restore EF1001
{
- private readonly JsonValueReaderWriter> _elementReaderWriter =
- (JsonValueReaderWriter>)elementReaderWriter;
+ private readonly JsonValueReaderWriter _elementReaderWriter = elementReaderWriter;
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -531,7 +556,7 @@ public override IEnumerable> FromJsonT
}
else
{
- dictionary.Add(key, (TConcreteCollection)_elementReaderWriter.FromJsonTyped(ref manager));
+ dictionary.Add(key, (TConcreteCollection)_elementReaderWriter.FromJson(ref manager));
}
break;
@@ -557,7 +582,7 @@ public override void ToJsonTyped(Utf8JsonWriter writer, IEnumerable(
JsonValueReaderWriter elementReaderWriter)
- : JsonValueReaderWriter>>, ICompositeJsonValueReaderWriter
+ : CosmosJsonStringKeyedDictionaryCollectionValueReaderWriter(elementReaderWriter)
where TConcreteCollection : IEnumerable
where TElement : class
#pragma warning restore EF1001
{
- private readonly JsonValueReaderWriter
public override SqlParameter CreateParameter(string name, object? value)
{
+ if (JsonValueReaderWriter != null)
+ {
+ value = value switch
+ {
+ ReadOnlyMemory memory when ClrType == typeof(byte[]) => memory.ToArray(),
+ ReadOnlyMemory memory when ClrType == typeof(sbyte[]) => memory.ToArray(),
+ ReadOnlyMemory memory when ClrType == typeof(float[]) => memory.ToArray(),
+ byte[] array when ClrType == typeof(ReadOnlyMemory) => ReadOnlyMemoryConverter.ToMemory(array),
+ sbyte[] array when ClrType == typeof(ReadOnlyMemory) => ReadOnlyMemoryConverter.ToMemory(array),
+ float[] array when ClrType == typeof(ReadOnlyMemory) => ReadOnlyMemoryConverter.ToMemory(array),
+ _ => value
+ };
+
+ return base.CreateParameter(name, value);
+ }
+
// This is a hack to write vector types of bytes as byte arrays in queries, instead of strings
if (value is ReadOnlyMemory romBytes)
{
diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
index 271a28c19e4..00e86183088 100644
--- a/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
+++ b/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
@@ -485,6 +486,20 @@ private string CreateModelBuilder(
.AppendLine("}")
.AppendLine();
+ foreach (var readerWriterType in model.GetTypeMappingConfigurations()
+ .Select(c => c.GetJsonValueReaderWriterType())
+ .OfType()
+ .Distinct())
+ {
+ AddNamespace(typeof(DynamicDependencyAttribute), namespaces);
+ AddNamespace(readerWriterType, namespaces);
+ mainBuilder
+ .Append("[DynamicDependency(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | ")
+ .Append("DynamicallyAccessedMemberTypes.PublicProperties, ")
+ .Append(_code.Literal(readerWriterType))
+ .AppendLine(")]");
+ }
+
mainBuilder
.AppendLine("partial void Initialize()")
.AppendLine("{");
@@ -698,6 +713,14 @@ private void Create(
.Append("()");
}
+ if (typeConfiguration.GetJsonValueReaderWriterType() is { } jsonValueReaderWriterType)
+ {
+ AddNamespace(jsonValueReaderWriterType, parameters.Namespaces);
+ mainBuilder.AppendLine(",")
+ .Append("jsonValueReaderWriterType: ")
+ .Append(_code.Literal(jsonValueReaderWriterType));
+ }
+
mainBuilder
.AppendLine(");")
.DecrementIndent();
diff --git a/src/EFCore.Relational/EFCore.Relational.baseline.json b/src/EFCore.Relational/EFCore.Relational.baseline.json
index 30b993fc6e2..71ad58fca41 100644
--- a/src/EFCore.Relational/EFCore.Relational.baseline.json
+++ b/src/EFCore.Relational/EFCore.Relational.baseline.json
@@ -12409,6 +12409,10 @@
{
"Member": "static System.Linq.Expressions.Expression QuoteTypeMapping(Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping? typeMapping);",
"Stage": "Experimental"
+ },
+ {
+ "Member": "static System.Linq.Expressions.Expression QuoteTypeMapping(Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping typeMapping, System.Type clrType);",
+ "Stage": "Experimental"
}
]
},
diff --git a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs
index d3b1cdc1bb4..a32cac68ce1 100644
--- a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs
+++ b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs
@@ -34,6 +34,12 @@ public class RelationalModelValidator(
///
protected virtual RelationalModelValidatorDependencies RelationalDependencies { get; } = relationalDependencies;
+ ///
+ protected override bool IsJsonProperty(IProperty property)
+ => (property.DeclaringType.IsMappedToJson() && property.GetJsonPropertyName() != null)
+ || (property.IsPrimitiveCollection
+ && property.GetTypeMapping().Converter?.ProviderClrType == typeof(string));
+
///
/// Validates a model, throwing an exception if any errors are found.
///
diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs
index 385fe72fc6f..f5ce6be9c50 100644
--- a/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs
+++ b/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs
@@ -45,13 +45,15 @@ public virtual void ProcessModelFinalizing(
{
foreach (var enumProperty in jsonEntityType
.GetDeclaredProperties()
- .Where(p => p.ClrType.UnwrapNullableType().IsEnum))
+ .Where(p => p.GetJsonPropertyName() != null && p.ClrType.UnwrapNullableType().IsEnum))
{
// If the enum is mapped with no conversion, then use the reader/writer that handles legacy string values and warns.
if (enumProperty.GetValueConverter() == null
- && enumProperty.GetProviderClrType() == null)
+ && enumProperty.GetProviderClrType() == null
+ && ((IModel)modelBuilder.Metadata).FindTypeMappingConfiguration(enumProperty.ClrType.UnwrapNullableType())
+ ?.GetJsonValueReaderWriterType() == null)
{
- enumProperty.SetJsonValueReaderWriterType(
+ enumProperty.Builder.HasJsonValueReaderWriter(
typeof(JsonWarningEnumReaderWriter<>).MakeGenericType(enumProperty.ClrType.UnwrapNullableType()));
}
}
diff --git a/src/EFCore.Relational/Query/Internal/RelationalJsonUtilities.cs b/src/EFCore.Relational/Query/Internal/RelationalJsonUtilities.cs
index fa48fa15bcb..81f5751e88e 100644
--- a/src/EFCore.Relational/Query/Internal/RelationalJsonUtilities.cs
+++ b/src/EFCore.Relational/Query/Internal/RelationalJsonUtilities.cs
@@ -2,8 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
+using System.Globalization;
using System.Text;
using System.Text.Json;
+using Microsoft.EntityFrameworkCore.Storage.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
@@ -21,6 +24,41 @@ public static class RelationalJsonUtilities
/// 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.
///
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ public static object? ReadJsonScalar(JsonElement element, object? value, JsonValueReaderWriter readerWriter)
+ => element.ValueKind switch
+ {
+ JsonValueKind.Null => null,
+ JsonValueKind.String => element.GetString(),
+ JsonValueKind.Number => (readerWriter is IJsonConvertedValueReaderWriter converted
+ ? converted.Converter.ConvertToProvider(value)
+ : value is Enum
+ ? Convert.ToDecimal(value, CultureInfo.InvariantCulture)
+ : value) ?? ReadNumber(element, readerWriter),
+ JsonValueKind.True => true,
+ JsonValueKind.False => false,
+ _ => element.GetRawText()
+ };
+
+ private static object ReadNumber(JsonElement element, JsonValueReaderWriter readerWriter)
+ {
+ var providerType = readerWriter is IJsonConvertedValueReaderWriter converted
+ ? converted.Converter.ProviderClrType
+ : readerWriter.ValueType;
+ return providerType.UnwrapNullableType() == typeof(decimal)
+ ? element.GetDecimal()
+ : element.TryGetInt64(out var number)
+ ? number
+ : (object)element.GetDouble();
+ }
+#pragma warning restore EF1001
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
public static readonly MethodInfo SerializeComplexTypeToJsonMethod =
typeof(RelationalJsonUtilities).GetTypeInfo().GetDeclaredMethod(nameof(SerializeComplexTypeToJson))!;
@@ -89,7 +127,7 @@ void WriteJsonObject(Utf8JsonWriter writer, IComplexType complexType, object? ob
Check.DebugAssert(jsonPropertyName is not null);
writer.WritePropertyName(jsonPropertyName);
- var jsonValueReaderWriter = property.GetJsonValueReaderWriter() ?? property.GetTypeMapping().JsonValueReaderWriter;
+ var jsonValueReaderWriter = property.GetTypeMapping().JsonValueReaderWriter;
var propertyValue = property.GetGetter().GetClrValue(objectValue);
if (propertyValue is null && jsonValueReaderWriter?.HandlesNullWrites != true)
diff --git a/src/EFCore.Relational/Query/Internal/RelationalParameterProcessor.cs b/src/EFCore.Relational/Query/Internal/RelationalParameterProcessor.cs
index bdb4b90c5ca..1fca8b15718 100644
--- a/src/EFCore.Relational/Query/Internal/RelationalParameterProcessor.cs
+++ b/src/EFCore.Relational/Query/Internal/RelationalParameterProcessor.cs
@@ -117,6 +117,9 @@ private SqlParameterExpression VisitSqlParameter(SqlParameterExpression paramete
if (_sqlParameters.TryGetValue(parameter.InvariantName, out var existingParameter)
&& existingParameter is { TypeMapping: { } existingTypeMapping }
&& string.Equals(existingTypeMapping.StoreType, typeMapping.StoreType, StringComparison.OrdinalIgnoreCase)
+ && existingTypeMapping.GetType() == typeMapping.GetType()
+ && existingTypeMapping.DbType == typeMapping.DbType
+ && ReferenceEquals(existingTypeMapping.JsonValueReaderWriter, typeMapping.JsonValueReaderWriter)
&& ((existingTypeMapping.Converter is null && typeMapping.Converter is null)
|| (existingTypeMapping.Converter is not null && existingTypeMapping.Converter.Equals(typeMapping.Converter))))
{
diff --git a/src/EFCore.Relational/Query/RelationalExpressionQuotingUtilities.cs b/src/EFCore.Relational/Query/RelationalExpressionQuotingUtilities.cs
index 8a0b8e0e1e4..df6329274f1 100644
--- a/src/EFCore.Relational/Query/RelationalExpressionQuotingUtilities.cs
+++ b/src/EFCore.Relational/Query/RelationalExpressionQuotingUtilities.cs
@@ -62,20 +62,32 @@ public static Expression QuoteOrNull(T? expression)
/// Quotes a relational type mapping.
///
public static Expression QuoteTypeMapping(RelationalTypeMapping? typeMapping)
- => typeMapping is null
- ? Constant(null, typeof(RelationalTypeMapping))
- : Call(
- RelationalTypeMappingSourceParameter,
- RelationalTypeMappingSourceFindMappingMethod,
- Constant(typeMapping.ClrType, typeof(Type)),
- Constant(typeMapping.StoreType, typeof(string)),
- Constant(false), // TODO: keyOrIndex not accessible
- Constant(typeMapping.IsUnicode, typeof(bool?)),
- Constant(typeMapping.Size, typeof(int?)),
- Constant(false, typeof(bool?)), // TODO: rowversion not accessible
- Constant(typeMapping.IsFixedLength, typeof(bool?)),
- Constant(typeMapping.Precision, typeof(int?)),
- Constant(typeMapping.Scale, typeof(int?)));
+ => typeMapping switch
+ {
+ null => Constant(null, typeof(RelationalTypeMapping)),
+ IRelationalQuotableExpression quotable => quotable.Quote(),
+ _ => QuoteTypeMapping(typeMapping, typeMapping.ClrType)
+ };
+
+ ///
+ /// Quotes a type mapping lookup using the given CLR type and the mapping's relational facets.
+ ///
+ /// The mapping supplying the relational facets.
+ /// The CLR type to look up, such as a converted mapping's provider type.
+ /// An expression that looks up the type mapping.
+ public static Expression QuoteTypeMapping(RelationalTypeMapping typeMapping, Type clrType)
+ => Call(
+ RelationalTypeMappingSourceParameter,
+ RelationalTypeMappingSourceFindMappingMethod,
+ Constant(clrType, typeof(Type)),
+ Constant(typeMapping.StoreType, typeof(string)),
+ Constant(false), // TODO: keyOrIndex not accessible
+ Constant(typeMapping.IsUnicode, typeof(bool?)),
+ Constant(typeMapping.Size, typeof(int?)),
+ Constant(false, typeof(bool?)), // TODO: rowversion not accessible
+ Constant(typeMapping.IsFixedLength, typeof(bool?)),
+ Constant(typeMapping.Precision, typeof(int?)),
+ Constant(typeMapping.Scale, typeof(int?)));
///
/// Quotes an .
diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.ExecuteUpdate.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.ExecuteUpdate.cs
index 7c95254cdac..64de822acf4 100644
--- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.ExecuteUpdate.cs
+++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.ExecuteUpdate.cs
@@ -3,8 +3,10 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
+using System.Text.Json;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
+using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.Storage.Json;
using static Microsoft.EntityFrameworkCore.Infrastructure.ExpressionExtensions;
@@ -20,6 +22,11 @@ public partial class RelationalQueryableMethodTranslatingExpressionVisitor
private static readonly MethodInfo ParameterJsonSerializerMethod =
typeof(RelationalQueryableMethodTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterJsonSerializer))!;
+ private static readonly MethodInfo RawParameterJsonSerializerMethod =
+ typeof(RelationalQueryableMethodTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(RawParameterJsonSerializer))!;
+
+ private HashSet? _jsonParameterNames;
+
///
protected override UpdateExpression TranslateExecuteUpdate(ShapedQueryExpression source, IReadOnlyList setters)
{
@@ -704,7 +711,7 @@ void ProcessStructuralJsonSetter(JsonQueryExpression jsonQuery)
case SqlParameterExpression parameter:
{
var queryParameter = _queryCompilationContext.RegisterRuntimeParameter(
- $"{ExecuteUpdateRuntimeParameterPrefix}{parameter.Name}",
+ GenerateJsonParameterName(parameter.InvariantName),
Expression.Lambda(
Expression.Call(
RelationalJsonUtilities.SerializeComplexTypeToJsonMethod,
@@ -713,13 +720,17 @@ void ProcessStructuralJsonSetter(JsonQueryExpression jsonQuery)
Expression.Property(
QueryCompilationContext.QueryContextParameter, nameof(QueryContext.Parameters)),
indexer: typeof(Dictionary).GetProperty("Item", [typeof(string)]),
- [Expression.Constant(parameter.Name, typeof(string))]),
+ [Expression.Constant(parameter.InvariantName, typeof(string))]),
Expression.Constant(jsonQuery.IsCollection)),
QueryCompilationContext.QueryContextParameter));
- serializedValue = _sqlExpressionFactory.ApplyTypeMapping(
- _sqlTranslator.Translate(queryParameter, applyDefaultTypeMapping: false),
- jsonColumn.TypeMapping)!;
+ serializedValue = new SqlParameterExpression(
+ invariantName: queryParameter.Name,
+ name: parameter.Name,
+ queryParameter.Type,
+ queryParameter.Type.IsNullableType(),
+ queryParameter.TranslationMode,
+ jsonColumn.TypeMapping);
break;
}
@@ -837,6 +848,18 @@ protected virtual bool TrySerializeScalarToJson(
var typeMapping = value.TypeMapping;
Check.DebugAssert(typeMapping is not null);
+ if (value is SqlConstantExpression or SqlParameterExpression)
+ {
+ jsonValue = SerializeJsonValue(value, target.TypeMapping!, raw: target.TypeMapping!.ElementTypeMapping is not null);
+ return jsonValue is not null;
+ }
+
+ if (!HaveCompatibleJsonRepresentations(target.TypeMapping!, value))
+ {
+ jsonValue = null;
+ return false;
+ }
+
// First, for the types natively supported in JSON (int, string, bool), just pass these in as is, since the JSON functions support these
// directly across databases.
var providerClrType = (typeMapping.Converter?.ProviderClrType ?? value.Type).UnwrapNullableType();
@@ -851,67 +874,20 @@ protected virtual bool TrySerializeScalarToJson(
Check.DebugAssert(typeMapping.JsonValueReaderWriter is not null, "Missing JsonValueReaderWriter on JSON property");
var stringTypeMapping = _typeMappingSource.FindMapping(typeof(string))!;
- switch (value)
+ if (value is JsonScalarExpression jsonScalarValue)
{
- // When an object is instantiated inline (e.g. SetProperty(c => c.ShippingAddress, c => new Address { ... })), we get a SqlConstantExpression
- // with the .NET instance. Serialize it to JSON and replace the constant.
- case SqlConstantExpression { Value: var constantValue }:
- {
- string? jsonString;
-
- if (constantValue is null)
- {
- jsonString = null;
- }
- else
- {
- // We should only be here for things that get serialized to strings.
- // Non-string JSON types (number, bool) should have been checked beforehand and handled differently.
- jsonString = typeMapping.JsonValueReaderWriter.ToJsonString(constantValue);
- Check.DebugAssert(jsonString.StartsWith('"') && jsonString.EndsWith('"'));
- jsonString = jsonString[1..^1];
- }
-
- jsonValue = new SqlConstantExpression(jsonString, typeof(string), stringTypeMapping);
- return true;
- }
-
- case SqlParameterExpression sqlParameter:
- {
- var queryParameter = _queryCompilationContext.RegisterRuntimeParameter(
- $"{ExecuteUpdateRuntimeParameterPrefix}{sqlParameter.Name}",
- Expression.Lambda(
- Expression.Call(
- ParameterJsonSerializerMethod,
- QueryCompilationContext.QueryContextParameter,
- Expression.Constant(sqlParameter.Name, typeof(string)),
- Expression.Constant(typeMapping.JsonValueReaderWriter, typeof(JsonValueReaderWriter))),
- QueryCompilationContext.QueryContextParameter));
- jsonValue = (SqlParameterExpression)_sqlExpressionFactory.ApplyTypeMapping(
- _sqlTranslator.Translate(queryParameter, applyDefaultTypeMapping: false),
- stringTypeMapping)!;
- return true;
- }
-
- case JsonScalarExpression jsonScalarValue:
- // The JSON scalar property is being assigned to another JSON scalar property.
- // In principle this is easy - just copy the property value across; but the JsonScalarExpression
- // is typed for its relational value (e.g. datetime2), which we can't pass the the partial update
- // function.
- // Since int and bool have been handled above, simply retype the JsonScalarExpression to return
- // a string instead, to get the raw JSON representation.
- jsonValue = new JsonScalarExpression(
- jsonScalarValue.Json,
- jsonScalarValue.Path,
- typeof(string),
- stringTypeMapping,
- jsonScalarValue.IsNullable);
- return true;
-
- default:
- jsonValue = null;
- return false;
+ // Copy the stored JSON representation rather than the relational value (e.g. datetime2).
+ jsonValue = new JsonScalarExpression(
+ jsonScalarValue.Json,
+ jsonScalarValue.Path,
+ typeof(string),
+ stringTypeMapping,
+ jsonScalarValue.IsNullable);
+ return true;
}
+
+ jsonValue = null;
+ return false;
}
///
@@ -934,6 +910,174 @@ protected virtual bool TrySerializeScalarToJson(
ref SqlExpression? existingSetterValue)
=> throw new InvalidOperationException(RelationalStrings.JsonPartialExecuteUpdateNotSupportedByProvider);
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ [EntityFrameworkInternal]
+ protected virtual bool HaveCompatibleJsonRepresentations(
+ RelationalTypeMapping targetMapping, SqlExpression source)
+ {
+ var sourceMapping = source.TypeMapping!;
+ var providerType = (sourceMapping.Converter?.ProviderClrType ?? sourceMapping.ClrType).UnwrapNullableType();
+ // Native scalar extraction loses the original token kind; collections retain their serialized elements.
+ var jsonSource = sourceMapping.ElementTypeMapping is not null
+ || (source is JsonScalarExpression
+ && !providerType.IsNumeric() && providerType != typeof(string) && providerType != typeof(bool));
+ return (source is JsonScalarExpression or ColumnExpression or SqlConstantExpression or SqlParameterExpression
+ || sourceMapping.Converter is null
+ || sourceMapping.Converter.ModelClrType == sourceMapping.Converter.ProviderClrType)
+ && HaveCompatibleJsonMappings(
+ targetMapping, sourceMapping, jsonSource);
+ }
+
+ private bool HaveCompatibleJsonMappings(
+ RelationalTypeMapping targetMapping, RelationalTypeMapping sourceMapping, bool jsonSource)
+ {
+ if (targetMapping.ElementTypeMapping is RelationalTypeMapping targetElementMapping
+ && sourceMapping.ElementTypeMapping is RelationalTypeMapping sourceElementMapping)
+ {
+ return HaveCompatibleJsonMappings(targetElementMapping, sourceElementMapping, jsonSource: true);
+ }
+
+ var providerType = (targetMapping.Converter?.ProviderClrType ?? targetMapping.ClrType).UnwrapNullableType();
+ if (providerType != (sourceMapping.Converter?.ProviderClrType ?? sourceMapping.ClrType).UnwrapNullableType()
+ || !ExpressionEqualityComparer.Instance.Equals(
+ targetMapping.Converter?.ConvertToProviderExpression, sourceMapping.Converter?.ConvertToProviderExpression)
+ || !ExpressionEqualityComparer.Instance.Equals(
+ targetMapping.Converter?.ConvertFromProviderExpression, sourceMapping.Converter?.ConvertFromProviderExpression))
+ {
+ return false;
+ }
+
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ var targetReader = targetMapping.JsonValueReaderWriter is IJsonConvertedValueReaderWriter targetConverted
+ ? targetConverted.InnerReaderWriter
+ : targetMapping.JsonValueReaderWriter;
+ var sourceReader = jsonSource
+ ? sourceMapping.JsonValueReaderWriter is IJsonConvertedValueReaderWriter sourceConverted
+ ? sourceConverted.InnerReaderWriter
+ : sourceMapping.JsonValueReaderWriter
+ : _typeMappingSource.FindMapping(providerType, storeTypeName: sourceMapping.StoreType)?.JsonValueReaderWriter;
+ if (!jsonSource
+ && targetReader is not null
+ && targetReader.GetType().IsGenericType
+ && targetReader.GetType().GetGenericTypeDefinition() is var readerType
+ && (readerType == typeof(JsonSignedEnumReaderWriter<>)
+ || readerType == typeof(JsonUnsignedEnumReaderWriter<>)))
+ {
+ // Built-in enum readers emit the same numbers as their underlying integral readers.
+ targetReader = _typeMappingSource.FindMapping(
+ Enum.GetUnderlyingType(targetReader.ValueType), storeTypeName: sourceMapping.StoreType)?.JsonValueReaderWriter;
+ }
+
+ return targetReader is not null
+ && sourceReader is not null
+ && ExpressionEqualityComparer.Instance.Equals(targetReader.ConstructorExpression, sourceReader.ConstructorExpression);
+#pragma warning restore EF1001
+ }
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ [EntityFrameworkInternal]
+ protected virtual SqlExpression? SerializeJsonValue(SqlExpression value, RelationalTypeMapping mapping, bool raw)
+ {
+ var readerWriter = mapping.JsonValueReaderWriter!;
+ var jsonTypeMapping = raw
+ ? _typeMappingSource.FindMapping(
+ typeof(string), storeTypeName: mapping.ElementTypeMapping is null ? null : mapping.StoreType)
+ : null;
+ switch (value)
+ {
+ case SqlConstantExpression constant:
+ var json = SerializeJson(constant.Value, readerWriter);
+ var scalar = raw ? json : ReadJsonScalar(json, constant.Value, readerWriter);
+ return new SqlConstantExpression(
+ scalar, scalar?.GetType() ?? typeof(string),
+ raw ? jsonTypeMapping : _typeMappingSource.FindMapping(scalar?.GetType() ?? typeof(string)));
+
+ case SqlParameterExpression parameter:
+ var queryParameter = _queryCompilationContext.RegisterRuntimeParameter(
+ GenerateJsonParameterName(parameter.InvariantName),
+ Expression.Lambda(
+ Expression.Call(
+ raw ? RawParameterJsonSerializerMethod : ParameterJsonSerializerMethod,
+ QueryCompilationContext.QueryContextParameter,
+ Expression.Constant(parameter.InvariantName),
+ Expression.Constant(readerWriter, typeof(JsonValueReaderWriter))),
+ QueryCompilationContext.QueryContextParameter));
+ return new SqlParameterExpression(
+ invariantName: queryParameter.Name,
+ name: parameter.Name,
+ queryParameter.Type,
+ queryParameter.Type.IsNullableType(),
+ queryParameter.TranslationMode,
+ raw
+ ? jsonTypeMapping
+ // The text-backed JSON mapping also supports scalars; native JSON parameters require documents.
+ : _typeMappingSource.FindMapping(
+ typeof(JsonTypePlaceholder), storeTypeName: _typeMappingSource.GetMapping(typeof(string)).StoreType));
+
+ default:
+ return null;
+ }
+ }
+
+ private string GenerateJsonParameterName(string baseName)
+ {
+ if (_jsonParameterNames is null)
+ {
+ _jsonParameterNames = [];
+ // Reserve parameters from the entire query, including setters which haven't been translated yet.
+ new JsonParameterNameCollectingExpressionVisitor(_jsonParameterNames).Visit(_rootExpression);
+ }
+
+ var name = Uniquifier.Uniquify($"json_{baseName}", _jsonParameterNames, maxLength: int.MaxValue);
+ _jsonParameterNames.Add(name);
+ return name;
+ }
+
+ private sealed class JsonParameterNameCollectingExpressionVisitor(HashSet parameterNames) : ExpressionVisitor
+ {
+ protected override Expression VisitExtension(Expression extensionExpression)
+ {
+ if (extensionExpression is QueryParameterExpression parameter)
+ {
+ parameterNames.Add(parameter.Name);
+ return parameter;
+ }
+
+ return base.VisitExtension(extensionExpression);
+ }
+ }
+
+ private static string SerializeJson(object? value, JsonValueReaderWriter readerWriter)
+ => value is null && !readerWriter.HandlesNullWrites ? "null" : readerWriter.ToJsonString(value);
+
+ private static object? ReadJsonScalar(string json, object? value, JsonValueReaderWriter readerWriter)
+ {
+ using var document = JsonDocument.Parse(json);
+ var element = document.RootElement;
+ return element.ValueKind is JsonValueKind.Object or JsonValueKind.Array
+ ? throw new InvalidOperationException(RelationalStrings.ExecuteUpdateCannotSetJsonPropertyToArbitraryExpression)
+ : RelationalJsonUtilities.ReadJsonScalar(element, value, readerWriter);
+ }
+
+ private static object? ParameterJsonSerializer(
+ QueryContext context, string parameterName, JsonValueReaderWriter readerWriter)
+ => ReadJsonScalar(
+ SerializeJson(context.Parameters[parameterName], readerWriter), context.Parameters[parameterName], readerWriter);
+
+ private static string RawParameterJsonSerializer(
+ QueryContext context, string parameterName, JsonValueReaderWriter readerWriter)
+ => SerializeJson(context.Parameters[parameterName], readerWriter);
+
private static T? ParameterValueExtractor(
QueryContext context,
string baseParameterName,
@@ -958,25 +1102,6 @@ protected virtual bool TrySerializeScalarToJson(
return baseValue == null ? (T?)(object?)null : (T?)property.GetGetter().GetClrValue(baseValue);
}
- private static string? ParameterJsonSerializer(
- QueryContext queryContext,
- string baseParameterName,
- JsonValueReaderWriter jsonValueReaderWriter)
- {
- var value = queryContext.Parameters[baseParameterName];
-
- if (value is null)
- {
- return null;
- }
-
- // We should only be here for things that get serialized to strings.
- // Non-string JSON types (number, bool, null) should have been checked beforehand and handled differently.
- var jsonString = jsonValueReaderWriter.ToJsonString(value);
- Check.DebugAssert(jsonString.StartsWith('"') && jsonString.EndsWith('"'));
- return jsonString[1..^1];
- }
-
private sealed class ParameterBasedComplexPropertyChainExpression(
SqlParameterExpression parameterExpression,
IComplexProperty firstComplexProperty)
diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
index 85a57e95a74..1b574c44d2a 100644
--- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
+++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
@@ -105,9 +105,6 @@ private static readonly MethodInfo Utf8GetBytesMethod
private static readonly PropertyInfo Utf8JsonReaderTokenTypeProperty
= typeof(Utf8JsonReader).GetProperty(nameof(Utf8JsonReader.TokenType))!;
- private static readonly MethodInfo PropertyGetJsonValueReaderWriterMethod =
- typeof(IReadOnlyProperty).GetMethod(nameof(IReadOnlyProperty.GetJsonValueReaderWriter), [])!;
-
private static readonly MethodInfo PropertyGetTypeMappingMethod =
typeof(IReadOnlyProperty).GetMethod(nameof(IReadOnlyProperty.GetTypeMapping), [])!;
@@ -3165,8 +3162,7 @@ Expression valueExpression
var jsonPrimitiveCollectionReaderWriter = converter is { ConvertsNulls: false, ProviderClrType: var providerClrType }
&& providerClrType == typeof(string)
? property is IProperty { IsPrimitiveCollection: true } primitiveCollectionProperty
- ? primitiveCollectionProperty.GetJsonValueReaderWriter()
- ?? primitiveCollectionProperty.GetTypeMapping().JsonValueReaderWriter
+ ? primitiveCollectionProperty.GetTypeMapping().JsonValueReaderWriter
: property is null && typeMapping.ElementTypeMapping is not null
? typeMapping.JsonValueReaderWriter
: null
@@ -3181,17 +3177,12 @@ Expression valueExpression
jsonReaderWriterExpression = _parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
jsonPrimitiveCollectionReaderWriter,
Lambda>(
- Coalesce(
+ Property(
Call(
LiftableConstantExpressionHelpers.BuildMemberAccessForProperty(
jsonProperty, liftableConstantParameter),
- PropertyGetJsonValueReaderWriterMethod),
- Property(
- Call(
- LiftableConstantExpressionHelpers.BuildMemberAccessForProperty(
- jsonProperty, liftableConstantParameter),
- PropertyGetTypeMappingMethod),
- nameof(CoreTypeMapping.JsonValueReaderWriter))),
+ PropertyGetTypeMappingMethod),
+ nameof(CoreTypeMapping.JsonValueReaderWriter)),
liftableConstantParameter),
jsonProperty.Name + "JsonReaderWriter",
typeof(JsonValueReaderWriter));
@@ -3416,20 +3407,16 @@ private Expression CreateReadJsonPropertyValueExpression(
ParameterExpression jsonReaderManagerParameter,
IProperty property)
{
- var jsonReaderWriter = property.GetJsonValueReaderWriter() ?? property.GetTypeMapping().JsonValueReaderWriter!;
+ var jsonReaderWriter = property.GetTypeMapping().JsonValueReaderWriter!;
var prm = Parameter(typeof(MaterializerLiftableConstantContext), "c");
var jsonReaderWriterExpression = _parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
- property.GetJsonValueReaderWriter() ?? property.GetTypeMapping().JsonValueReaderWriter!,
+ property.GetTypeMapping().JsonValueReaderWriter!,
Lambda>(
- Coalesce(
+ Property(
Call(
LiftableConstantExpressionHelpers.BuildMemberAccessForProperty(property, prm),
- PropertyGetJsonValueReaderWriterMethod),
- Property(
- Call(
- LiftableConstantExpressionHelpers.BuildMemberAccessForProperty(property, prm),
- PropertyGetTypeMappingMethod),
- nameof(CoreTypeMapping.JsonValueReaderWriter))),
+ PropertyGetTypeMappingMethod),
+ nameof(CoreTypeMapping.JsonValueReaderWriter)),
prm),
property.Name + "PropertyName",
jsonReaderWriter.GetType());
@@ -3440,17 +3427,12 @@ private Expression CreateReadJsonPropertyValueExpression(
Expression resultExpression = Convert(
Call(jsonReaderWriterExpression, fromJsonMethod, jsonReaderManagerParameter, Default(typeof(object))),
- property.GetTypeMapping().ClrType);
+ property.ClrType);
if (property.IsNullable)
{
// in case of null value we can't just use the JsonReader method, but rather check the current token type
// if it's JsonTokenType.Null means value is null, only if it's not we are safe to read the value
- if (resultExpression.Type != property.ClrType)
- {
- resultExpression = Convert(resultExpression, property.ClrType);
- }
-
var converter = property.GetTypeMapping().Converter;
Expression nullExpression;
if (converter?.ConvertsNulls == true)
@@ -3518,11 +3500,6 @@ private Expression CreateReadJsonPropertyValueExpression(
// as empty, the same as an absent key and as the Cosmos provider does, when the collection type is one the reader/writer
// itself would create. A property-level reader/writer decides how its collection is created, so for one of those the
// clear, property-named error stays instead of the cryptic reader/writer "Invalid token type". See #38625 and #34881.
- if (resultExpression.Type != property.ClrType)
- {
- resultExpression = Convert(resultExpression, property.ClrType);
- }
-
resultExpression = Condition(
Equal(
Property(
diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs
index 071a037676e..e540935c99c 100644
--- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs
+++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs
@@ -645,11 +645,11 @@ bool TryGeneratePregeneratedCommandResolver(
if (parameter.IsNullable)
{
nullableParameterList.Add(parameter);
- parameters[parameter.Name] = null;
+ parameters[parameter.InvariantName] = null;
}
else
{
- parameters[parameter.Name] = GenerateNonNullParameterValue(parameter.Type);
+ parameters[parameter.InvariantName] = GenerateNonNullParameterValue(parameter.Type);
}
}
@@ -698,20 +698,20 @@ Expression Core(int parameterIndex)
if (parameterIndex < numNullableParameters - 1)
{
var parameter = nullableParameterList[parameterIndex];
- parameters[parameter.Name] = null;
+ parameters[parameter.InvariantName] = null;
ifNull = Core(parameterIndex + 1);
if (!canCache)
{
return null!;
}
- parameters[parameter.Name] = GenerateNonNullParameterValue(parameter.Type);
+ parameters[parameter.InvariantName] = GenerateNonNullParameterValue(parameter.Type);
ifNotNull = Core(parameterIndex + 1);
ifThenElse =
IfThenElse(
Equal(
- Property(parameterDictionaryParameter, "Item", Constant(currentParameter.Name)),
+ Property(parameterDictionaryParameter, "Item", Constant(currentParameter.InvariantName)),
Constant(null, typeof(object))),
ifNull,
ifNotNull);
@@ -730,7 +730,7 @@ Expression Core(int parameterIndex)
ifThenElse =
IfThenElse(
Equal(
- Property(parameterDictionaryParameter, "Item", Constant(currentParameter.Name)),
+ Property(parameterDictionaryParameter, "Item", Constant(currentParameter.InvariantName)),
Constant(null, typeof(object))),
Assign(resultParameter, ifNull),
Assign(resultParameter, ifNotNull));
@@ -743,7 +743,7 @@ Expression Core(int parameterIndex)
Expression LastParameter(bool withNull)
{
var parameter = nullableParameterList[parameterIndex];
- parameters[parameter.Name] = withNull ? null : GenerateNonNullParameterValue(parameter.Type);
+ parameters[parameter.InvariantName] = withNull ? null : GenerateNonNullParameterValue(parameter.Type);
return GenerateRelationalCommandExpression(parameters, out canCache);
}
diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs
index 81439d73c52..1bd2de84c10 100644
--- a/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs
+++ b/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs
@@ -106,9 +106,10 @@ public override bool Equals(object? obj)
private bool Equals(SqlParameterExpression sqlParameterExpression)
=> base.Equals(sqlParameterExpression)
+ && InvariantName == sqlParameterExpression.InvariantName
&& Name == sqlParameterExpression.Name;
///
public override int GetHashCode()
- => HashCode.Combine(base.GetHashCode(), Name);
+ => HashCode.Combine(base.GetHashCode(), InvariantName, Name);
}
diff --git a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs
index 922926e6a80..ca069abd256 100644
--- a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs
+++ b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs
@@ -1841,7 +1841,7 @@ protected virtual SqlExpression VisitSqlParameter(
bool allowOptimizedExpansion,
out bool nullable)
{
- if (ParametersDecorator.IsNull(sqlParameterExpression.Name))
+ if (ParametersDecorator.IsNull(sqlParameterExpression.InvariantName))
{
nullable = true;
@@ -1858,7 +1858,7 @@ protected virtual SqlExpression VisitSqlParameter(
var parameters = ParametersDecorator.GetAndDisableCaching();
return _sqlExpressionFactory.Constant(
- parameters[sqlParameterExpression.Name],
+ parameters[sqlParameterExpression.InvariantName],
sqlParameterExpression.Type,
sensitive: true,
sqlParameterExpression.TypeMapping);
@@ -2463,7 +2463,7 @@ private SqlExpression ProcessNullNotNull(SqlExpression sqlExpression, bool opera
// not_null_value_parameter is null -> false
// not_null_value_parameter is not null -> true
return _sqlExpressionFactory.Constant(
- ParametersDecorator.IsNull(sqlParameterOperand.Name) ^ sqlUnaryExpression.OperatorType == ExpressionType.NotEqual,
+ ParametersDecorator.IsNull(sqlParameterOperand.InvariantName) ^ sqlUnaryExpression.OperatorType == ExpressionType.NotEqual,
sqlUnaryExpression.TypeMapping);
case ColumnExpression columnOperand
diff --git a/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs b/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs
index c0a274c7c34..a780d18c2a3 100644
--- a/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs
+++ b/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs
@@ -272,16 +272,14 @@ public RelationalTypeMappingInfo(
int? precision = null,
int? scale = null)
{
- _coreTypeMappingInfo = new TypeMappingInfo(
- typeMappingConfiguration.GetValueConverter()?.ProviderClrType ?? type,
- elementTypeMapping,
- keyOrIndex: false,
- unicode ?? typeMappingConfiguration.IsUnicode(),
- size ?? typeMappingConfiguration.GetMaxLength(),
- rowVersion: false,
- precision ?? typeMappingConfiguration.GetPrecision(),
- scale ?? typeMappingConfiguration.GetScale(),
- key: false);
+ _coreTypeMappingInfo = new TypeMappingInfo(type, typeMappingConfiguration, elementTypeMapping) with
+ {
+ IsUnicode = unicode ?? typeMappingConfiguration.IsUnicode(),
+ Size = size ?? typeMappingConfiguration.GetMaxLength(),
+ IsRowVersion = false,
+ Precision = precision ?? typeMappingConfiguration.GetPrecision(),
+ Scale = scale ?? typeMappingConfiguration.GetScale()
+ };
IsFixedLength = (bool?)typeMappingConfiguration[RelationalAnnotationNames.IsFixedLength];
StoreTypeName = storeTypeName;
diff --git a/src/EFCore.Relational/Storage/RelationalTypeMappingSource.cs b/src/EFCore.Relational/Storage/RelationalTypeMappingSource.cs
index a07aa17c599..addb63df543 100644
--- a/src/EFCore.Relational/Storage/RelationalTypeMappingSource.cs
+++ b/src/EFCore.Relational/Storage/RelationalTypeMappingSource.cs
@@ -182,9 +182,7 @@ protected override RelationalTypeMapping FindMapping(in TypeMappingInfo mappingI
if (mapping != null)
{
- mapping = (RelationalTypeMapping)mapping.WithComposedConverter(
- secondConverterInfo.Create(),
- jsonValueReaderWriter: mappingInfoUsed.JsonValueReaderWriter);
+ mapping = (RelationalTypeMapping)mapping.WithComposedConverter(secondConverterInfo.Create());
break;
}
}
@@ -192,9 +190,7 @@ protected override RelationalTypeMapping FindMapping(in TypeMappingInfo mappingI
if (mapping != null)
{
- mapping = (RelationalTypeMapping)mapping.WithComposedConverter(
- converterInfo.Create(),
- jsonValueReaderWriter: mappingInfo.JsonValueReaderWriter);
+ mapping = (RelationalTypeMapping)mapping.WithComposedConverter(converterInfo.Create());
break;
}
}
@@ -205,9 +201,19 @@ protected override RelationalTypeMapping FindMapping(in TypeMappingInfo mappingI
if (mapping != null
&& customConverter != null)
{
- mapping = (RelationalTypeMapping)mapping.WithComposedConverter(
- customConverter,
- jsonValueReaderWriter: mappingInfo.JsonValueReaderWriter);
+ mapping = (RelationalTypeMapping)mapping.WithComposedConverter(customConverter);
+ }
+
+ if (mapping != null
+ && mappingInfo.JsonValueReaderWriter != null)
+ {
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ var readerWriter = mappingInfo.JsonValueReaderWriter;
+ mapping = (RelationalTypeMapping)(mapping.Converter is { } converter
+ && !readerWriter.ValueType.UnwrapNullableType().IsAssignableFrom(converter.ProviderClrType.UnwrapNullableType())
+ ? mapping.Clone(jsonValueReaderWriter: readerWriter)
+ : mapping.WithJsonValueReaderWriter(readerWriter));
+#pragma warning restore EF1001
}
return mapping;
@@ -368,12 +374,24 @@ protected override RelationalTypeMapping FindMapping(in TypeMappingInfo mappingI
var mappingInfo = new RelationalTypeMappingInfo(
type, typeConfiguration, (RelationalTypeMapping?)elementMapping,
storeTypeName, storeTypeNameBase, unicode, size, precision, scale);
+ mappingInfo = mappingInfo with
+ {
+ // An inferred element mapping defines collection parameter transport, not document formatting.
+ JsonValueReaderWriter = elementMapping == null ? mappingInfo.JsonValueReaderWriter : null,
+ ElementTypeMapping = (RelationalTypeMapping?)elementMapping
+ ?? (RelationalTypeMapping?)FindElementMapping(mappingInfo.CoreTypeMappingInfo, model)
+ };
var providerClrType = typeConfiguration.GetProviderClrType()?.UnwrapNullableType();
return FindMappingWithConversion(mappingInfo, providerClrType, customConverter: typeConfiguration.GetValueConverter());
}
+ var defaultMappingInfo = new RelationalTypeMappingInfo(type, (RelationalTypeMapping?)elementMapping);
return FindMappingWithConversion(
- new RelationalTypeMappingInfo(type, (RelationalTypeMapping?)elementMapping),
+ defaultMappingInfo with
+ {
+ ElementTypeMapping = (RelationalTypeMapping?)elementMapping
+ ?? (RelationalTypeMapping?)FindElementMapping(defaultMappingInfo.CoreTypeMappingInfo, model)
+ },
providerClrType: null,
customConverter: null);
}
diff --git a/src/EFCore.Relational/Update/ModificationCommand.cs b/src/EFCore.Relational/Update/ModificationCommand.cs
index dbddb9d1466..bb8ee6e78ff 100644
--- a/src/EFCore.Relational/Update/ModificationCommand.cs
+++ b/src/EFCore.Relational/Update/ModificationCommand.cs
@@ -8,6 +8,8 @@
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
using IColumnMapping = Microsoft.EntityFrameworkCore.Metadata.IColumnMapping;
using ITableMapping = Microsoft.EntityFrameworkCore.Metadata.ITableMapping;
@@ -1030,36 +1032,27 @@ static IEnumerable GetJsonComplexProperties(IEntityType entity
/// Performs processing specifically needed for column modifications that correspond to single-property JSON updates.
///
///
- /// By default, strings, numeric types and bool and sent as a regular relational parameter, since database functions responsible for
- /// patching JSON documents support this. Other types get converted to JSON via the normal means and sent as a string parameter.
+ /// Values are serialized through the property's JSON reader/writer. Scalars are sent as relational values,
+ /// while objects and arrays are sent as JSON text.
///
protected virtual void ProcessSinglePropertyJsonUpdate(ref ColumnModificationParameters parameters)
{
var property = parameters.Property!;
- var mapping = property.GetRelationalTypeMapping();
- var propertyProviderClrType = (mapping.Converter?.ProviderClrType ?? property.ClrType).UnwrapNullableType();
+ var readerWriter = property.GetRelationalTypeMapping().JsonValueReaderWriter!;
var value = parameters.Value;
-
- // On most databases, the function which patches a JSON document (e.g. SQL Server JSON_MODIFY) accepts relational string, numeric
- // and bool types directly, without serializing it to a JSON string. So by default, for those cases simply return the value as-is,
- // with the property's type mapping which will take care of sending the parameter with the relational value.
- // Note that we haven't yet applied a value converter if one is configured, in order to allow for it to get applied later with
- // the regular parameter flow.
- if (value == null
- || propertyProviderClrType == typeof(string)
- || propertyProviderClrType == typeof(bool)
- || propertyProviderClrType.IsNumeric())
- {
- parameters = parameters with { Value = value, TypeMapping = mapping };
- }
- else
+ using var document = JsonDocument.Parse(
+ value is null && !readerWriter.HandlesNullWrites ? "null" : readerWriter.ToJsonString(value));
+ var element = document.RootElement;
+ value = Query.Internal.RelationalJsonUtilities.ReadJsonScalar(element, value, readerWriter);
+ parameters = parameters with
{
- var jsonValueReaderWriter = mapping.JsonValueReaderWriter;
- value = jsonValueReaderWriter?.ToJsonString(value)[1..^1] // The JSON string contains enclosing quotes, remove these.
- ?? (mapping.Converter == null ? value : mapping.Converter.ConvertToProvider(value));
-
- parameters = parameters with { Value = value };
- }
+ Value = value,
+ TypeMapping = element.ValueKind is JsonValueKind.Object or JsonValueKind.Array
+ ? parameters.TypeMapping
+ // JSON numbers are not limited to a relational column's default precision and scale.
+ : ((IRelationalTypeMappingSource)property.DeclaringType.Model.GetModelDependencies().TypeMappingSource)
+ .GetMapping(value?.GetType() ?? typeof(string)).WithPrecisionAndScale(null, null)
+ };
}
private void WriteJson(
@@ -1148,7 +1141,7 @@ private void WriteJsonObject(
var propertyValue = entry.GetCurrentValue(property);
writer.WritePropertyName(jsonPropertyName);
- var jsonValueReaderWriter = property.GetJsonValueReaderWriter() ?? property.GetTypeMapping().JsonValueReaderWriter;
+ var jsonValueReaderWriter = property.GetTypeMapping().JsonValueReaderWriter;
if (propertyValue is not null || jsonValueReaderWriter?.HandlesNullWrites == true)
{
Check.DebugAssert(jsonValueReaderWriter is not null, "Missing JsonValueReaderWriter on JSON property");
diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs
index 5ebacbbe9e6..ead882d49c6 100644
--- a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs
+++ b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryableMethodTranslatingExpressionVisitor.cs
@@ -1014,6 +1014,13 @@ protected override bool TrySerializeScalarToJson(
}
#pragma warning restore EF9002
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ if (!HaveCompatibleJsonRepresentations(target.TypeMapping!, value))
+ {
+ return false;
+ }
+#pragma warning restore EF1001
+
// geometry/geography are "user-defined types" and therefore not supported by JSON_OBJECT(), which we
// use below for serializing arbitrary relational expressions to JSON. Special-case them and serialize
// as WKT.
diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs
index aed39c7873d..acd154e4287 100644
--- a/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs
+++ b/src/EFCore.SqlServer/Query/Internal/SqlServerTypeMappingPostprocessor.cs
@@ -74,26 +74,15 @@ protected virtual SqlServerOpenJsonExpression ApplyTypeMappingsOnOpenJsonExpress
// 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
+ if (!TryGetInferredTypeMapping(openJsonExpression.Alias, "value", out var elementTypeMapping))
{
// 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 })
+ if (_typeMappingSource.FindMapping(parameterExpression.Type, _model)
+ is not { ElementTypeMapping: RelationalTypeMapping e })
{
throw new UnreachableException("Default type mapping has no element type mapping");
}
@@ -101,6 +90,17 @@ protected virtual SqlServerOpenJsonExpression ApplyTypeMappingsOnOpenJsonExpress
elementTypeMapping = e;
}
+ // OPENJSON's WITH clause reads native provider values, independently of document formatting.
+ if (_typeMappingSource.FindMapping(elementTypeMapping.Converter?.ProviderClrType ?? elementTypeMapping.ClrType)
+ ?.JsonValueReaderWriter is { } nativeReaderWriter)
+ {
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ elementTypeMapping = (RelationalTypeMapping)elementTypeMapping.WithJsonValueReaderWriter(nativeReaderWriter);
+#pragma warning restore EF1001
+ }
+
+ var parameterTypeMapping = _typeMappingSource.FindMapping(parameterExpression.Type, _model, elementTypeMapping);
+
return parameterTypeMapping is not SqlServerStringTypeMapping { ElementTypeMapping: not null }
and not SqlServerJsonTypeMapping { ElementTypeMapping: not null }
? throw new UnreachableException("A string/JSON collection type mapping was not found")
diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerStructuralJsonTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerStructuralJsonTypeMapping.cs
index bd556cff703..56ef301025a 100644
--- a/src/EFCore.SqlServer/Storage/Internal/SqlServerStructuralJsonTypeMapping.cs
+++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerStructuralJsonTypeMapping.cs
@@ -150,6 +150,20 @@ protected override void ConfigureParameter(DbParameter parameter)
sqlParameter.SqlDbType = SqlDbType.Json;
}
+ if (parameter.Value is null or DBNull or string)
+ {
+ var length = (parameter.Value as string)?.Length ?? 0;
+ var maxSpecificSize = Size is > 0 and <= 4000 ? Size.Value : 4000;
+
+ // Bucket text parameters like regular Unicode strings to avoid query cache fragmentation.
+ parameter.Size = length <= maxSpecificSize ? maxSpecificSize : length <= 4000 ? 4000 : -1;
+ }
+ else
+ {
+ // A serialized scalar can be numeric or Boolean; let the driver infer its native type and precision.
+ parameter.ResetDbType();
+ }
+
base.ConfigureParameter(parameter);
}
}
diff --git a/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommand.cs b/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommand.cs
index afd3efc45f5..7f46d58d144 100644
--- a/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommand.cs
+++ b/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommand.cs
@@ -1,8 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
-
namespace Microsoft.EntityFrameworkCore.SqlServer.Update.Internal;
///
@@ -34,83 +32,4 @@ public SqlServerModificationCommand(in NonTrackedModificationCommandParameters m
: base(modificationCommandParameters)
{
}
-
- ///
- /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
- /// the same compatibility standards as public APIs. It may be changed or removed without notice in
- /// 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 override void ProcessSinglePropertyJsonUpdate(ref ColumnModificationParameters parameters)
- {
- // TODO: Move more of this logic to the type mapping. Issue #38036
- var property = parameters.Property!;
- var mapping = property.GetRelationalTypeMapping();
- var propertyProviderClrType = (mapping.Converter?.ProviderClrType ?? property.ClrType).UnwrapNullableType();
- var value = parameters.Value;
-
- // A null value is sent as a NULL parameter. JSON_MODIFY rejects parameters whose type can't be implicitly
- // converted to nvarchar (e.g. date/time types), even when the value itself is null. Since the value is null the
- // parameter type doesn't affect the result, so keep the property's mapping only for types that JSON_MODIFY
- // accepts directly (string, bool, numeric) and otherwise fall back to a string mapping.
- if (value is null)
- {
- parameters = parameters with
- {
- TypeMapping = propertyProviderClrType == typeof(string)
- || propertyProviderClrType == typeof(bool)
- || propertyProviderClrType.IsNumeric()
- ? mapping
- : SqlServerStringTypeMapping.UnicodeDefault
- };
-
- return;
- }
-
- // JSON-compatible non-string values (bool, numeric) are sent directly as non-string parameters.
- if ((propertyProviderClrType == typeof(bool)
- || propertyProviderClrType.IsNumeric())
- && !property.IsPrimitiveCollection)
- {
- parameters = parameters with { Value = value, TypeMapping = mapping };
-
- return;
- }
-
- var jsonValueReaderWriter = mapping.JsonValueReaderWriter;
- if (jsonValueReaderWriter != null)
- {
- if (property.IsPrimitiveCollection)
- {
- // This is a JSON array, so send with the original type mapping, which may indicate the column type is JSON.
- parameters = parameters with { Value = jsonValueReaderWriter.ToJsonString(value) };
-
- return;
- }
-
- // Otherwise, wrap the value in a simple JSON object to avoid double escaping.
- parameters = parameters with
- {
- Value = jsonValueReaderWriter.ToJsonObjectString("", value),
- TypeMapping = parameters.TypeMapping is SqlServerStructuralJsonTypeMapping
- ? parameters.TypeMapping
- : SqlServerStructuralJsonTypeMapping.Default
- };
-
- return;
- }
-
- if (mapping.Converter != null)
- {
- value = mapping.Converter.ConvertToProvider(value);
- }
-
- parameters = parameters with
- {
- Value = value,
- TypeMapping = parameters.TypeMapping is SqlServerStructuralJsonTypeMapping
- ? SqlServerStringTypeMapping.UnicodeDefault
- : parameters.TypeMapping
- };
- }
}
diff --git a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs
index 1999f30bd98..e23abe11c64 100644
--- a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs
+++ b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs
@@ -4,6 +4,7 @@
using System.Data;
using System.Globalization;
using System.Text;
+using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
namespace Microsoft.EntityFrameworkCore.SqlServer.Update.Internal;
@@ -154,26 +155,15 @@ protected override void AppendUpdateColumnValue(
stringBuilder.Append(", 'strict ");
columnModification.JsonPath.AppendTo(stringBuilder);
stringBuilder.Append("', ");
- var mapping = columnModification.Property?.GetRelationalTypeMapping();
- var propertyProviderClrType = (mapping?.Converter?.ProviderClrType ?? columnModification.Property?.ClrType)?.UnwrapNullableType();
-
- if (columnModification.Value is null
- || propertyProviderClrType == typeof(bool)
- || (propertyProviderClrType != null && propertyProviderClrType.IsNumeric()))
- {
- base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
- }
- else if (columnModification.Property is { IsPrimitiveCollection: false })
+ if (columnModification.TypeMapping is SqlServerStructuralJsonTypeMapping)
{
- stringBuilder.Append("JSON_VALUE(");
+ stringBuilder.Append("JSON_QUERY(");
base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
- stringBuilder.Append(", '$.\"\"')");
+ stringBuilder.Append(")");
}
else
{
- stringBuilder.Append("JSON_QUERY(");
base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
- stringBuilder.Append(")");
}
stringBuilder.Append(")");
diff --git a/src/EFCore.Sqlite.Core/Design/Internal/SqliteCSharpRuntimeAnnotationCodeGenerator.cs b/src/EFCore.Sqlite.Core/Design/Internal/SqliteCSharpRuntimeAnnotationCodeGenerator.cs
index 226ec885c1e..a8e66591a5d 100644
--- a/src/EFCore.Sqlite.Core/Design/Internal/SqliteCSharpRuntimeAnnotationCodeGenerator.cs
+++ b/src/EFCore.Sqlite.Core/Design/Internal/SqliteCSharpRuntimeAnnotationCodeGenerator.cs
@@ -3,6 +3,7 @@
using Microsoft.EntityFrameworkCore.Design.Internal;
using Microsoft.EntityFrameworkCore.Sqlite.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
namespace Microsoft.EntityFrameworkCore.Sqlite.Design.Internal;
@@ -64,4 +65,21 @@ public override void Generate(IColumn column, CSharpRuntimeAnnotationCodeGenerat
base.Generate(column, parameters);
}
+
+ ///
+ protected override CoreTypeMapping? CreateDefaultTypeMapping(
+ CoreTypeMapping typeMapping,
+ CSharpRuntimeAnnotationCodeGeneratorParameters parameters)
+ {
+ if (typeMapping is not SqliteJsonScalarTypeMapping jsonMapping)
+ {
+ return base.CreateDefaultTypeMapping(typeMapping, parameters);
+ }
+
+ AddNamespace(typeof(SqliteJsonScalarTypeMapping), parameters.Namespaces);
+ parameters.MainBuilder.Append("new SqliteJsonScalarTypeMapping(");
+ Create(jsonMapping.SourceMapping, parameters);
+ parameters.MainBuilder.Append(")");
+ return new SqliteJsonScalarTypeMapping(jsonMapping.SourceMapping);
+ }
}
diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQuerySqlGenerator.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQuerySqlGenerator.cs
index 944c950ebc8..545e243a536 100644
--- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQuerySqlGenerator.cs
+++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQuerySqlGenerator.cs
@@ -3,6 +3,7 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
+using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal;
diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs
index 5bc49334e55..f49398ed57b 100644
--- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs
+++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs
@@ -5,6 +5,7 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Sqlite.Internal;
+using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal;
@@ -712,14 +713,6 @@ bool TryTranslate(
projectionColumn.TypeMapping,
projectionColumn.IsNullable);
- // If we have a type mapping (i.e. translating over a column rather than a parameter), apply any necessary server-side
- // conversions.
- if (projectionColumn.TypeMapping is not null)
- {
- translation = ApplyJsonSqlConversion(
- translation, _sqlExpressionFactory, projectionColumn.TypeMapping, projectionColumn.IsNullable);
- }
-
#pragma warning disable EF1001
result = source.UpdateQueryExpression(new SelectExpression(translation, _sqlAliasManager));
#pragma warning restore EF1001
@@ -742,6 +735,25 @@ protected override bool TrySerializeScalarToJson(
SqlExpression value,
[NotNullWhen(true)] out SqlExpression? jsonValue)
{
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ if (value is SqlConstantExpression or SqlParameterExpression)
+ {
+ var serialized = SerializeJsonValue(value, target.TypeMapping!, raw: true);
+ jsonValue = serialized is null
+ ? null
+ : _sqlExpressionFactory.Function(
+ "json", [serialized], nullable: true, argumentsPropagateNullability: [true],
+ typeof(string), _typeMappingSource.FindMapping(typeof(string)));
+ return jsonValue is not null;
+ }
+
+ if (!HaveCompatibleJsonRepresentations(target.TypeMapping!, value))
+ {
+ jsonValue = null;
+ return false;
+ }
+#pragma warning restore EF1001
+
var providerClrType = (value.TypeMapping!.Converter?.ProviderClrType ?? value.Type).UnwrapNullableType();
// SQLite has no bool type, so if we simply sent the bool as-is, we'd get 1/0 in the JSON document.
@@ -909,7 +921,7 @@ public static SqlExpression ApplyJsonSqlConversion(
// hex string or NULL, hence unhex simply propagates the nullability
// from its argument.
- ByteArrayTypeMapping
+ _ when (typeMapping.Converter?.ProviderClrType ?? typeMapping.ClrType) == typeof(byte[])
=> sqlExpressionFactory.Function(
"unhex",
[expression],
diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteTypeMappingPostprocessor.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteTypeMappingPostprocessor.cs
index 8425d1f6fc5..3d379c7f341 100644
--- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteTypeMappingPostprocessor.cs
+++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteTypeMappingPostprocessor.cs
@@ -46,6 +46,13 @@ protected override Expression VisitExtension(Expression expression)
{
switch (expression)
{
+ case JsonScalarExpression { TypeMapping: { } scalarMapping } jsonScalarExpression:
+ return SqliteQueryableMethodTranslatingExpressionVisitor.ApplyJsonSqlConversion(
+ (SqlExpression)base.VisitExtension(jsonScalarExpression),
+ _sqlExpressionFactory,
+ scalarMapping,
+ jsonScalarExpression.IsNullable);
+
case JsonEachExpression jsonEachExpression
when TryGetInferredTypeMapping(
jsonEachExpression.Alias,
@@ -119,7 +126,18 @@ protected virtual JsonEachExpression ApplyTypeMappingsOnJsonEachExpression(
return jsonEachExpression;
}
- if (_typeMappingSource.FindMapping(parameterExpression.Type, _model, inferredTypeMapping) is not SqliteStringTypeMapping
+ var elementTypeMapping = inferredTypeMapping;
+ if (elementTypeMapping is not SqliteJsonScalarTypeMapping
+ && _typeMappingSource.FindMapping(elementTypeMapping.Converter?.ProviderClrType ?? elementTypeMapping.ClrType)
+ ?.JsonValueReaderWriter is { } nativeReaderWriter)
+ {
+#pragma warning disable EF1001 // Internal EF Core API usage.
+ elementTypeMapping = (RelationalTypeMapping)elementTypeMapping.WithJsonValueReaderWriter(
+ nativeReaderWriter);
+#pragma warning restore EF1001
+ }
+
+ if (_typeMappingSource.FindMapping(parameterExpression.Type, _model, elementTypeMapping) is not SqliteStringTypeMapping
parameterTypeMapping)
{
throw new InvalidOperationException("Type mapping for 'string' could not be found or was not a SqliteStringTypeMapping");
diff --git a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteByteArrayTypeMapping.cs b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteByteArrayTypeMapping.cs
index 6b8ef509a66..e2bccc551a7 100644
--- a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteByteArrayTypeMapping.cs
+++ b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteByteArrayTypeMapping.cs
@@ -35,48 +35,26 @@ public SqliteByteArrayTypeMapping(string storeType, DbType? dbType = System.Data
typeof(byte[]),
jsonValueReaderWriter: SqliteJsonByteArrayReaderWriter.Instance),
storeType,
- dbType: dbType),
- false)
+ dbType: dbType))
{
}
- private SqliteByteArrayTypeMapping(
- RelationalTypeMappingParameters parameters,
- bool isJsonColumn)
- : base(parameters)
- {
- _isJsonColumn = isJsonColumn;
- }
-
- private readonly bool _isJsonColumn;
-
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// 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 SqliteByteArrayTypeMapping(RelationalTypeMappingParameters parameters)
+ : base(parameters)
+ {
+ }
+
///
/// Creates a copy of this mapping.
///
/// The parameters for this mapping.
/// The newly created mapping.
protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
- => new SqliteByteArrayTypeMapping(parameters, _isJsonColumn);
-
- internal SqliteByteArrayTypeMapping WithJsonColumn(bool jsonColumn = true)
- => new(Parameters, jsonColumn);
-
- ///
- /// Configures the parameter, setting the to
- /// when the mapping is for a JSON column.
- ///
- /// The parameter to be configured.
- protected override void ConfigureParameter(DbParameter parameter)
- {
- if (_isJsonColumn && parameter is Data.Sqlite.SqliteParameter sqliteParameter)
- {
- sqliteParameter.SqliteType = Data.Sqlite.SqliteType.Text;
- }
- }
+ => new SqliteByteArrayTypeMapping(parameters);
}
diff --git a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonScalarTypeMapping.cs b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonScalarTypeMapping.cs
new file mode 100644
index 00000000000..9572abca1e6
--- /dev/null
+++ b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonScalarTypeMapping.cs
@@ -0,0 +1,172 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Data;
+using System.Globalization;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore.Query;
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
+namespace Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
+
+///
+/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+/// the same compatibility standards as public APIs. It may be changed or removed without notice in
+/// 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.
+///
+public class SqliteJsonScalarTypeMapping : RelationalTypeMapping, IRelationalQuotableExpression
+{
+ private static readonly ConstructorInfo _quotingConstructor
+ = typeof(SqliteJsonScalarTypeMapping).GetConstructor([typeof(RelationalTypeMapping)])!;
+
+ private static readonly MethodInfo _withComposedConverterMethod
+ = typeof(RelationalTypeMapping).GetMethod(
+ nameof(WithComposedConverter),
+ [
+ typeof(ValueConverter), typeof(ValueComparer), typeof(ValueComparer), typeof(CoreTypeMapping), typeof(JsonValueReaderWriter)
+ ])!;
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public SqliteJsonScalarTypeMapping(RelationalTypeMapping mapping)
+ : this(
+ new RelationalTypeMappingParameters(
+ new CoreTypeMappingParameters(
+ mapping.ClrType, mapping.Converter, mapping.Comparer, mapping.KeyComparer, mapping.ProviderValueComparer,
+ elementMapping: mapping.ElementTypeMapping, jsonValueReaderWriter: mapping.JsonValueReaderWriter),
+ mapping.StoreType, mapping.StoreTypePostfix, mapping.DbType, mapping.IsUnicode,
+ mapping.Size, mapping.IsFixedLength, mapping.Precision, mapping.Scale),
+ mapping)
+ {
+ }
+
+ private SqliteJsonScalarTypeMapping(
+ RelationalTypeMappingParameters parameters,
+ RelationalTypeMapping sourceMapping)
+ : base(parameters)
+ {
+ SourceMapping = sourceMapping;
+ }
+
+ internal RelationalTypeMapping SourceMapping { get; }
+
+ ///
+ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
+ => new SqliteJsonScalarTypeMapping(
+ parameters,
+ parameters.CoreParameters.Converter == SourceMapping.Converter
+ ? SourceMapping
+ : SourceMapping.Clone(converter: parameters.CoreParameters.Converter));
+
+ ///
+ public virtual Expression Quote()
+ {
+ var sourceMapping = SourceMapping.WithStoreTypeAndSize(StoreType, Size).WithPrecisionAndScale(Precision, Scale);
+ var sourceExpression = SourceMapping.Converter is { } converter
+ ? RelationalExpressionQuotingUtilities.QuoteTypeMapping(sourceMapping, converter.ProviderClrType)
+ : RelationalExpressionQuotingUtilities.QuoteTypeMapping(sourceMapping);
+
+ return Expression.New(
+ _quotingConstructor,
+ Expression.Convert(
+ Expression.Call(
+ sourceExpression,
+ _withComposedConverterMethod,
+ Expression.Constant(SourceMapping.Converter, typeof(ValueConverter)),
+ Expression.Constant(null, typeof(ValueComparer)),
+ Expression.Constant(null, typeof(ValueComparer)),
+ Expression.Constant(null, typeof(CoreTypeMapping)),
+ JsonValueReaderWriter!.ConstructorExpression),
+ typeof(RelationalTypeMapping)));
+ }
+
+ ///
+ public override Expression GenerateCodeLiteral(object value)
+ => SourceMapping.GenerateCodeLiteral(value);
+
+ ///
+ public override MethodInfo GetDataReaderMethod()
+ => SourceMapping.GetDataReaderMethod();
+
+ ///
+ public override Expression CustomizeDataReaderExpression(Expression expression)
+ => SourceMapping.CustomizeDataReaderExpression(expression);
+
+ ///
+ public override DbParameter CreateParameter(
+ DbCommand command,
+ string name,
+ object? value,
+ bool? nullable = null,
+ ParameterDirection direction = ParameterDirection.Input)
+ => (Converter?.ProviderClrType ?? ClrType) == typeof(byte[])
+ ? SourceMapping.CreateParameter(command, name, value, nullable, direction)
+ : CreateJsonParameter(this, command, name, value, nullable, direction);
+
+ ///
+ public override string GenerateSqlLiteral(object? value)
+ => (Converter?.ProviderClrType ?? ClrType) == typeof(byte[])
+ ? SourceMapping.GenerateSqlLiteral(value)
+ : GenerateJsonSqlLiteral(this, value);
+
+ internal static DbParameter CreateJsonParameter(
+ RelationalTypeMapping mapping,
+ DbCommand command,
+ string name,
+ object? value,
+ bool? nullable,
+ ParameterDirection direction)
+ {
+ var (scalar, scalarMapping) = Serialize(mapping, value);
+ return scalarMapping.CreateParameter(command, name, scalar, nullable, direction);
+ }
+
+ internal static string GenerateJsonSqlLiteral(RelationalTypeMapping mapping, object? value)
+ {
+ var (scalar, scalarMapping) = Serialize(mapping, value);
+ return scalarMapping.GenerateSqlLiteral(scalar);
+ }
+
+ private static (object? Value, RelationalTypeMapping Mapping) Serialize(RelationalTypeMapping mapping, object? value)
+ {
+ var readerWriter = mapping.JsonValueReaderWriter!;
+ if (value is null && !readerWriter.HandlesNullWrites)
+ {
+ return (null, SqliteStringTypeMapping.Default);
+ }
+
+ if (value is not null && !mapping.ClrType.IsInstanceOfType(value))
+ {
+ if (mapping.Converter is null
+ && mapping.ClrType != typeof(char)
+ && mapping.ClrType.IsInteger()
+ && value.GetType().IsInteger())
+ {
+ // A promoted comparison operand need not fit in the property's CLR range.
+ return (value, LongTypeMapping.Default);
+ }
+
+ value = mapping.ClrType.IsEnum
+ ? Enum.ToObject(mapping.ClrType, value)
+ : Convert.ChangeType(value, mapping.ClrType.UnwrapNullableType(), CultureInfo.InvariantCulture);
+ }
+
+ using var document = JsonDocument.Parse(readerWriter.ToJsonString(value));
+ var element = document.RootElement;
+ return element.ValueKind switch
+ {
+ JsonValueKind.Null => (null, SqliteStringTypeMapping.Default),
+ JsonValueKind.String => (element.GetString(), SqliteStringTypeMapping.Default),
+ JsonValueKind.Number when element.TryGetInt64(out var number) => (number, LongTypeMapping.Default),
+ JsonValueKind.Number => (element.GetDouble(), DoubleTypeMapping.Default),
+ JsonValueKind.True => (1L, LongTypeMapping.Default),
+ JsonValueKind.False => (0L, LongTypeMapping.Default),
+ _ => (element.GetRawText(), SqliteStringTypeMapping.Default)
+ };
+ }
+}
diff --git a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs
index 1cc96c0ae27..a974760401f 100644
--- a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs
+++ b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs
@@ -1,6 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Storage.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
namespace Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;
///
@@ -140,21 +143,27 @@ public static bool IsSpatialiteType(string columnType)
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
///
- /// Finds the type mapping for a given property. This method is overridden to special-case byte[]
- /// properties inside JSON columns, returning a mapping that works with hex-encoded string representation.
+ /// Finds the type mapping for a given property, accounting for its JSON representation.
///
/// The property for which mapping is to be found.
/// The type mapping, or if none was found.
public override RelationalTypeMapping? FindMapping(IProperty property)
{
var mapping = base.FindMapping(property);
- if (mapping is SqliteByteArrayTypeMapping byteArrayMapping && property.DeclaringType.IsMappedToJson())
- {
- return byteArrayMapping.WithJsonColumn();
- }
- return mapping;
+ return property.DeclaringType.IsMappedToJson() ? FindJsonMapping(mapping) : mapping;
}
+ ///
+ public override RelationalTypeMapping? FindMapping(IElementType elementType)
+ => FindJsonMapping(base.FindMapping(elementType));
+
+ private static RelationalTypeMapping? FindJsonMapping(RelationalTypeMapping? mapping)
+ => mapping is null or SqliteJsonScalarTypeMapping
+ || mapping.ElementTypeMapping is not null
+ || mapping.JsonValueReaderWriter is null
+ ? mapping
+ : new SqliteJsonScalarTypeMapping(mapping);
+
private RelationalTypeMapping? FindRawMapping(RelationalTypeMappingInfo mappingInfo)
{
var clrType = mappingInfo.ClrType;
diff --git a/src/EFCore.Sqlite.Core/Update/Internal/SqliteModificationCommand.cs b/src/EFCore.Sqlite.Core/Update/Internal/SqliteModificationCommand.cs
index 56f3b884ed5..99bbb29da3f 100644
--- a/src/EFCore.Sqlite.Core/Update/Internal/SqliteModificationCommand.cs
+++ b/src/EFCore.Sqlite.Core/Update/Internal/SqliteModificationCommand.cs
@@ -41,34 +41,12 @@ public SqliteModificationCommand(in NonTrackedModificationCommandParameters modi
///
protected override void ProcessSinglePropertyJsonUpdate(ref ColumnModificationParameters parameters)
{
- var property = parameters.Property!;
-
- var propertyProviderClrType = (property.GetTypeMapping().Converter?.ProviderClrType ?? property.ClrType).UnwrapNullableType();
-
- // SQLite has no bool type, so if we simply sent the bool as-is, we'd get 1/0 in the JSON document.
- // To get an actual unquoted true/false value, we pass "true"/"false" string through the json() minifier, which does this.
- // See https://sqlite.org/forum/info/91d09974c3754ea6.
- // Here we convert the .NET bool to a "true"/"false" string, and SqliteUpdateSqlGenerator will add the enclosing json().
- if (propertyProviderClrType == typeof(bool))
+ var readerWriter = parameters.Property!.GetTypeMapping().JsonValueReaderWriter!;
+ parameters = parameters with
{
- var value = property.GetTypeMapping().Converter is { } converter
- ? converter.ConvertToProvider(parameters.Value)
- : parameters.Value;
-
- parameters = parameters with
- {
- Value = value switch
- {
- true => "true",
- false => "false",
- null => null,
- _ => throw new UnreachableException()
- }
- };
-
- return;
- }
-
- base.ProcessSinglePropertyJsonUpdate(ref parameters);
+ Value = parameters.Value is null && !readerWriter.HandlesNullWrites
+ ? "null"
+ : readerWriter.ToJsonString(parameters.Value)
+ };
}
}
diff --git a/src/EFCore.Sqlite.Core/Update/Internal/SqliteUpdateSqlGenerator.cs b/src/EFCore.Sqlite.Core/Update/Internal/SqliteUpdateSqlGenerator.cs
index 710ff5edd82..b4fb8ec2504 100644
--- a/src/EFCore.Sqlite.Core/Update/Internal/SqliteUpdateSqlGenerator.cs
+++ b/src/EFCore.Sqlite.Core/Update/Internal/SqliteUpdateSqlGenerator.cs
@@ -157,33 +157,9 @@ protected override void AppendUpdateColumnValue(
columnModification.JsonPath.AppendTo(stringBuilder);
stringBuilder.Append("', ");
- if (columnModification.Property is { IsPrimitiveCollection: false })
- {
- var providerClrType = (columnModification.Property.GetTypeMapping().Converter?.ProviderClrType
- ?? columnModification.Property.ClrType).UnwrapNullableType();
-
- // SQLite has no bool type, so if we simply sent the bool as-is, we'd get 1/0 in the JSON document.
- // To get an actual unquoted true/false value, we pass "true"/"false" string through the json() minifier, which does this.
- // See https://sqlite.org/forum/info/91d09974c3754ea6.
- // SqliteModificationCommand converted the .NET bool to a "true"/"false" string, here we add the enclosing json().
- if (providerClrType == typeof(bool))
- {
- stringBuilder.Append("json(");
- }
-
- base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
-
- if (providerClrType == typeof(bool))
- {
- stringBuilder.Append(")");
- }
- }
- else
- {
- stringBuilder.Append("json(");
- base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
- stringBuilder.Append(")");
- }
+ stringBuilder.Append("json(");
+ base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
+ stringBuilder.Append(")");
stringBuilder.Append(")");
}
diff --git a/src/EFCore/EFCore.baseline.json b/src/EFCore/EFCore.baseline.json
index 037c4535a39..35071be74d2 100644
--- a/src/EFCore/EFCore.baseline.json
+++ b/src/EFCore/EFCore.baseline.json
@@ -1285,6 +1285,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasSentinel(object? sentinel);"
},
@@ -1382,6 +1388,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexCollectionTypePropertyBuilder HasSentinel(object? sentinel);"
},
@@ -2113,6 +2125,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasMaxLength(int maxLength);"
},
@@ -2240,6 +2258,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ComplexTypePropertyBuilder HasMaxLength(int maxLength);"
},
@@ -4159,6 +4183,15 @@
{
"Member": "static string JsonReaderInvalidTokenType(object? tokenType);"
},
+ {
+ "Member": "static string JsonValueReaderWriterOnNonJsonProperty(object? structuralType, object? property, object? readerWriter);"
+ },
+ {
+ "Member": "static string JsonValueReaderWriterOnPrimitiveCollection(object? structuralType, object? property);"
+ },
+ {
+ "Member": "static string JsonValueReaderWriterPropertyMismatch(object? structuralType, object? property, object? readerWriter, object? valueType, object? storeType);"
+ },
{
"Member": "static string KeyAttributeOnDerivedEntity(object? derivedType, object? property, object? rootType);"
},
@@ -6722,6 +6755,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ElementTypeBuilder HasConversion(System.Type conversionType, System.Type? comparerType);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ElementTypeBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ElementTypeBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.ElementTypeBuilder HasMaxLength(int maxLength);"
},
@@ -9690,6 +9729,9 @@
{
"Member": "bool CanSetIsUnicode(bool? unicode, bool fromDataAnnotation = false);"
},
+ {
+ "Member": "bool CanSetJsonValueReaderWriter(System.Type? readerWriterType, bool fromDataAnnotation = false);"
+ },
{
"Member": "bool CanSetMaxLength(int? maxLength, bool fromDataAnnotation = false);"
},
@@ -9720,6 +9762,9 @@
{
"Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionElementTypeBuilder? HasConverter(System.Type? converterType, bool fromDataAnnotation = false);"
},
+ {
+ "Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionElementTypeBuilder? HasJsonValueReaderWriter(System.Type? readerWriterType, bool fromDataAnnotation = false);"
+ },
{
"Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionElementTypeBuilder? HasMaxLength(int? maxLength, bool fromDataAnnotation = false);"
},
@@ -11170,6 +11215,9 @@
{
"Member": "bool CanSetIsUnicode(bool? unicode, bool fromDataAnnotation = false);"
},
+ {
+ "Member": "bool CanSetJsonValueReaderWriter(System.Type? readerWriterType, bool fromDataAnnotation = false);"
+ },
{
"Member": "bool CanSetMaxLength(int? maxLength, bool fromDataAnnotation = false);"
},
@@ -11215,6 +11263,9 @@
{
"Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionPropertyBuilder? HasConverter(System.Type? converterType, bool fromDataAnnotation = false);"
},
+ {
+ "Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionPropertyBuilder? HasJsonValueReaderWriter(System.Type? readerWriterType, bool fromDataAnnotation = false);"
+ },
{
"Member": "Microsoft.EntityFrameworkCore.Metadata.Builders.IConventionPropertyBuilder? HasMaxLength(int? maxLength, bool fromDataAnnotation = false);"
},
@@ -16048,6 +16099,9 @@
{
"Type": "interface Microsoft.EntityFrameworkCore.Metadata.ITypeMappingConfiguration : Microsoft.EntityFrameworkCore.Infrastructure.IAnnotatable, Microsoft.EntityFrameworkCore.Infrastructure.IReadOnlyAnnotatable",
"Methods": [
+ {
+ "Member": "System.Type? GetJsonValueReaderWriterType();"
+ },
{
"Member": "int? GetMaxLength();"
},
@@ -17941,6 +17995,9 @@
{
"Member": "ModelValidator(Microsoft.EntityFrameworkCore.Infrastructure.ModelValidatorDependencies dependencies);"
},
+ {
+ "Member": "virtual bool IsJsonProperty(Microsoft.EntityFrameworkCore.Metadata.IProperty property);"
+ },
{
"Member": "virtual bool IsOwned(System.Type targetType, Microsoft.EntityFrameworkCore.Metadata.IModel model);"
},
@@ -19561,6 +19618,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasMaxLength(int maxLength);"
},
@@ -19691,6 +19754,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasField(string fieldName);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.PropertyBuilder HasMaxLength(int maxLength);"
},
@@ -21627,7 +21696,7 @@
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.RuntimeEntityType AddEntityType(string name, System.Type type, Microsoft.EntityFrameworkCore.Metadata.RuntimeEntityType? baseType = null, bool sharedClrType = false, Microsoft.EntityFrameworkCore.ChangeTrackingStrategy changeTrackingStrategy = Microsoft.EntityFrameworkCore.ChangeTrackingStrategy.Snapshot, System.Reflection.PropertyInfo? indexerPropertyInfo = null, bool propertyBag = false, string? discriminatorProperty = null, object? discriminatorValue = null, int derivedTypesCount = 0, int propertyCount = 0, int complexPropertyCount = 0, int navigationCount = 0, int skipNavigationCount = 0, int servicePropertyCount = 0, int foreignKeyCount = 0, int unnamedIndexCount = 0, int namedIndexCount = 0, int keyCount = 0, int triggerCount = 0);"
},
{
- "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.RuntimeTypeMappingConfiguration AddTypeMappingConfiguration(System.Type clrType, int? maxLength = null, bool? unicode = null, int? precision = null, int? scale = null, System.Type? providerPropertyType = null, Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter? valueConverter = null);"
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.RuntimeTypeMappingConfiguration AddTypeMappingConfiguration(System.Type clrType, int? maxLength = null, bool? unicode = null, int? precision = null, int? scale = null, System.Type? providerPropertyType = null, Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter? valueConverter = null, System.Type? jsonValueReaderWriterType = null);"
},
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.RuntimeEntityType? FindAdHocEntityType(System.Type clrType);"
@@ -23171,6 +23240,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasConversion(System.Type conversionType);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasMaxLength(int maxLength);"
},
@@ -23200,6 +23275,12 @@
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasConversion(System.Type conversionType);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasJsonValueReaderWriter() where TReaderWriter : Microsoft.EntityFrameworkCore.Storage.Json.JsonValueReaderWriter;"
+ },
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasJsonValueReaderWriter(System.Type? readerWriterType);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder HasMaxLength(int maxLength);"
},
@@ -23307,6 +23388,9 @@
{
"Member": "TypeMappingSourceBase(Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies dependencies);"
},
+ {
+ "Member": "virtual Microsoft.EntityFrameworkCore.Storage.CoreTypeMapping? FindElementMapping(Microsoft.EntityFrameworkCore.Storage.TypeMappingInfo mappingInfo, Microsoft.EntityFrameworkCore.Metadata.IModel model);"
+ },
{
"Member": "virtual Microsoft.EntityFrameworkCore.Storage.CoreTypeMapping? FindMapping(in Microsoft.EntityFrameworkCore.Storage.TypeMappingInfo mappingInfo);"
},
diff --git a/src/EFCore/Infrastructure/ModelValidator.cs b/src/EFCore/Infrastructure/ModelValidator.cs
index 27a206d54c9..6f4d6d6e47e 100644
--- a/src/EFCore/Infrastructure/ModelValidator.cs
+++ b/src/EFCore/Infrastructure/ModelValidator.cs
@@ -6,6 +6,7 @@
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Infrastructure;
@@ -1358,6 +1359,12 @@ protected virtual void ValidateTypeMapping(
IProperty property,
IDiagnosticsLogger logger)
{
+ ValidateJsonValueReaderWriter(property, null);
+ if (property.GetElementType() is { } elementType)
+ {
+ ValidateJsonValueReaderWriter(property, elementType);
+ }
+
var converter = property.GetValueConverter();
if (converter != null
&& property[CoreAnnotationNames.ValueComparer] == null)
@@ -1399,6 +1406,79 @@ protected virtual void ValidateTypeMapping(
}
}
+ ///
+ /// Returns whether a property or its primitive collection elements are stored as JSON.
+ ///
+ /// The property.
+ /// Whether the property is stored as JSON.
+ protected virtual bool IsJsonProperty(IProperty property)
+ => false;
+
+ private void ValidateJsonValueReaderWriter(IProperty property, IElementType? elementType)
+ {
+ var configurationSource = elementType == null
+ ? (property as IConventionProperty)?.GetJsonValueReaderWriterTypeConfigurationSource()
+ : (elementType as IConventionElementType)?.GetJsonValueReaderWriterTypeConfigurationSource();
+ var isConfigured = configurationSource.Overrides(ConfigurationSource.Convention);
+ var jsonProperty = IsJsonProperty(property);
+ if (!isConfigured && !jsonProperty)
+ {
+ return;
+ }
+
+ var clrType = (elementType?.ClrType ?? property.ClrType).UnwrapNullableType();
+ var readerWriter = isConfigured
+ ? elementType == null
+ ? property.GetJsonValueReaderWriter()
+ : elementType.GetJsonValueReaderWriter()
+ : property.DeclaringType.Model.FindTypeMappingConfiguration(clrType) is { } configuration
+ ? new TypeMappingInfo(clrType, configuration).JsonValueReaderWriter
+ : null;
+ if (readerWriter == null)
+ {
+ return;
+ }
+
+ var memberName = elementType == null ? property.Name : property.Name + "[]";
+ if (elementType == null
+ ? property.IsPrimitiveCollection
+ : elementType.GetTypeMapping().ElementTypeMapping != null)
+ {
+ throw new InvalidOperationException(
+ CoreStrings.JsonValueReaderWriterOnPrimitiveCollection(property.DeclaringType.DisplayName(), memberName));
+ }
+
+ if (!jsonProperty)
+ {
+ throw new InvalidOperationException(
+ CoreStrings.JsonValueReaderWriterOnNonJsonProperty(
+ property.DeclaringType.DisplayName(), memberName, readerWriter.GetType().ShortDisplayName()));
+ }
+
+ var mapping = elementType == null ? property.GetTypeMapping() : elementType.GetTypeMapping();
+ var converter = mapping.Converter;
+ var storeType = (converter != null
+ && !converter.GetType().GetGenericTypeImplementations(typeof(CollectionToJsonStringConverter<>)).Any()
+ ? converter.ProviderClrType
+ : elementType?.ClrType ?? property.ClrType).UnwrapNullableType();
+ if (clrType.IsEnum
+ && readerWriter.ValueType.UnwrapNullableType() == clrType
+ && storeType.IsNumeric()
+ && converter?.GetType().GetGenericTypeImplementations(typeof(EnumToNumberConverter<,>)).Any() == true)
+ {
+ // Enum readers can serialize the enum directly instead of using its numeric converter.
+ storeType = clrType;
+ }
+
+ if (!readerWriter.ValueType.UnwrapNullableType().IsAssignableFrom(storeType))
+ {
+ throw new InvalidOperationException(
+ CoreStrings.JsonValueReaderWriterPropertyMismatch(
+ property.DeclaringType.DisplayName(), memberName, readerWriter.GetType().ShortDisplayName(),
+ readerWriter.ValueType.ShortDisplayName(), storeType.ShortDisplayName()));
+ }
+ }
+
///
/// Validates that an entity type is not accidentally mapped from common CLR types.
///
diff --git a/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder.cs b/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder.cs
index 916deafceaf..4364644ae69 100644
--- a/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder.cs
+++ b/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder.cs
@@ -3,6 +3,7 @@
using System.ComponentModel;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -514,6 +515,37 @@ public virtual ComplexCollectionTypePropertyBuilder HasConversion(
return this;
}
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// This configuration overrides the model-wide JSON reader/writer default for the property's CLR type.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => HasJsonValueReaderWriter(typeof(TReaderWriter));
+
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// Clearing this configuration restores the model-wide default or the provider's JSON reader/writer.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type, or to clear the configuration.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ {
+ Builder.HasJsonValueReaderWriter(readerWriterType, ConfigurationSource.Explicit);
+
+ return this;
+ }
+
#region Hidden System.Object members
///
diff --git a/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder`.cs b/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder`.cs
index 20abd63f039..ed9cd244ba5 100644
--- a/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder`.cs
+++ b/src/EFCore/Metadata/Builders/ComplexCollectionTypePropertyBuilder`.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
///
@@ -30,6 +32,15 @@ public ComplexCollectionTypePropertyBuilder(IMutableProperty property)
{
}
+ ///
+ public new virtual ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => (ComplexCollectionTypePropertyBuilder)base.HasJsonValueReaderWriter();
+
+ ///
+ public new virtual ComplexCollectionTypePropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ => (ComplexCollectionTypePropertyBuilder)base.HasJsonValueReaderWriter(readerWriterType);
+
///
/// Adds or updates an annotation on the property. If an annotation with the key specified in
/// already exists its value will be updated.
diff --git a/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder.cs b/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder.cs
index 6735267e59c..b437906620a 100644
--- a/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder.cs
+++ b/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder.cs
@@ -3,6 +3,7 @@
using System.ComponentModel;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -651,6 +652,37 @@ public virtual ComplexTypePropertyBuilder HasConversion(
return this;
}
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// This configuration overrides the model-wide JSON reader/writer default for the property's CLR type.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ComplexTypePropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => HasJsonValueReaderWriter(typeof(TReaderWriter));
+
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// Clearing this configuration restores the model-wide default or the provider's JSON reader/writer.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type, or to clear the configuration.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ComplexTypePropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ {
+ Builder.HasJsonValueReaderWriter(readerWriterType, ConfigurationSource.Explicit);
+
+ return this;
+ }
+
#region Hidden System.Object members
///
diff --git a/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder`.cs b/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder`.cs
index 5794c683573..60e82ba3380 100644
--- a/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder`.cs
+++ b/src/EFCore/Metadata/Builders/ComplexTypePropertyBuilder`.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
///
@@ -30,6 +32,15 @@ public ComplexTypePropertyBuilder(IMutableProperty property)
{
}
+ ///
+ public new virtual ComplexTypePropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => (ComplexTypePropertyBuilder)base.HasJsonValueReaderWriter();
+
+ ///
+ public new virtual ComplexTypePropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ => (ComplexTypePropertyBuilder)base.HasJsonValueReaderWriter(readerWriterType);
+
///
/// Adds or updates an annotation on the property. If an annotation with the key specified in
/// already exists its value will be updated.
diff --git a/src/EFCore/Metadata/Builders/ElementTypeBuilder.cs b/src/EFCore/Metadata/Builders/ElementTypeBuilder.cs
index c32e720c438..61820dc8801 100644
--- a/src/EFCore/Metadata/Builders/ElementTypeBuilder.cs
+++ b/src/EFCore/Metadata/Builders/ElementTypeBuilder.cs
@@ -3,6 +3,7 @@
using System.ComponentModel;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -274,6 +275,37 @@ public virtual ElementTypeBuilder HasConversion(
return this;
}
+ ///
+ /// Configures the JSON reader/writer for the store values of elements of the collection.
+ ///
+ ///
+ /// The collection must be stored as JSON. When an element value converter is used, the reader/writer must handle
+ /// the converter's provider values. This configuration overrides the model-wide default for the element's CLR type.
+ /// To change the provider representation for server-side queries, configure an element value converter as well.
+ ///
+ /// The JSON reader/writer type.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ElementTypeBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => HasJsonValueReaderWriter(typeof(TReaderWriter));
+
+ ///
+ /// Configures the JSON reader/writer for the store values of elements of the collection.
+ ///
+ ///
+ /// The collection must be stored as JSON. When an element value converter is used, the reader/writer must handle
+ /// the converter's provider values. Clearing this configuration restores the model-wide default or the provider's reader/writer.
+ /// To change the provider representation for server-side queries, configure an element value converter as well.
+ ///
+ /// The JSON reader/writer type, or to clear the configuration.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual ElementTypeBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ {
+ Builder.HasJsonValueReaderWriter(readerWriterType, ConfigurationSource.Explicit);
+
+ return this;
+ }
+
#region Hidden System.Object members
///
diff --git a/src/EFCore/Metadata/Builders/IConventionElementTypeBuilder.cs b/src/EFCore/Metadata/Builders/IConventionElementTypeBuilder.cs
index d0c65f86594..fd27bd4c773 100644
--- a/src/EFCore/Metadata/Builders/IConventionElementTypeBuilder.cs
+++ b/src/EFCore/Metadata/Builders/IConventionElementTypeBuilder.cs
@@ -245,6 +245,25 @@ bool CanSetConverter(
Type? converterType,
bool fromDataAnnotation = false);
+ ///
+ /// Configures the JSON reader/writer for elements of the collection.
+ ///
+ ///
+ /// A type that inherits from ,
+ /// or to use the reader/writer from the type mapping.
+ ///
+ /// Indicates whether the configuration was specified using a data annotation.
+ /// The same builder if the configuration was applied, or otherwise.
+ IConventionElementTypeBuilder? HasJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation = false);
+
+ ///
+ /// Returns whether the JSON reader/writer can be configured from the current configuration source.
+ ///
+ /// The reader/writer type, or to remove the configuration.
+ /// Indicates whether the configuration was specified using a data annotation.
+ /// if the JSON reader/writer can be configured.
+ bool CanSetJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation = false);
+
///
/// Configures the for elements of the collection.
///
diff --git a/src/EFCore/Metadata/Builders/IConventionPropertyBuilder.cs b/src/EFCore/Metadata/Builders/IConventionPropertyBuilder.cs
index 531d5a70427..743e2dfcff0 100644
--- a/src/EFCore/Metadata/Builders/IConventionPropertyBuilder.cs
+++ b/src/EFCore/Metadata/Builders/IConventionPropertyBuilder.cs
@@ -441,6 +441,25 @@ bool CanSetConverter(
Type? converterType,
bool fromDataAnnotation = false);
+ ///
+ /// Configures the JSON reader/writer for this property.
+ ///
+ ///
+ /// A type that inherits from ,
+ /// or to use the reader/writer from the type mapping.
+ ///
+ /// Indicates whether the configuration was specified using a data annotation.
+ /// The same builder if the configuration was applied, or otherwise.
+ IConventionPropertyBuilder? HasJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation = false);
+
+ ///
+ /// Returns whether the JSON reader/writer can be configured from the current configuration source.
+ ///
+ /// The reader/writer type, or to remove the configuration.
+ /// Indicates whether the configuration was specified using a data annotation.
+ /// if the JSON reader/writer can be configured.
+ bool CanSetJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation = false);
+
///
/// Configures the for this property.
///
diff --git a/src/EFCore/Metadata/Builders/PropertyBuilder.cs b/src/EFCore/Metadata/Builders/PropertyBuilder.cs
index 5fd073c41c1..26d766b04f4 100644
--- a/src/EFCore/Metadata/Builders/PropertyBuilder.cs
+++ b/src/EFCore/Metadata/Builders/PropertyBuilder.cs
@@ -3,6 +3,7 @@
using System.ComponentModel;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -692,6 +693,37 @@ public virtual PropertyBuilder HasConversion(
return this;
}
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// This configuration overrides the model-wide JSON reader/writer default for the property's CLR type.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual PropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => HasJsonValueReaderWriter(typeof(TReaderWriter));
+
+ ///
+ /// Configures the JSON reader/writer for this property's store values. The property must be mapped to JSON.
+ ///
+ ///
+ /// When a value converter is used, the reader/writer must handle the converter's provider values.
+ /// Clearing this configuration restores the model-wide default or the provider's JSON reader/writer.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type, or to clear the configuration.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual PropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ {
+ Builder.HasJsonValueReaderWriter(readerWriterType, ConfigurationSource.Explicit);
+
+ return this;
+ }
+
#region Hidden System.Object members
///
diff --git a/src/EFCore/Metadata/Builders/PropertyBuilder`.cs b/src/EFCore/Metadata/Builders/PropertyBuilder`.cs
index 930d02e329c..9dc76bc853b 100644
--- a/src/EFCore/Metadata/Builders/PropertyBuilder`.cs
+++ b/src/EFCore/Metadata/Builders/PropertyBuilder`.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
///
@@ -30,6 +32,15 @@ public PropertyBuilder(IMutableProperty property)
{
}
+ ///
+ public new virtual PropertyBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => (PropertyBuilder)base.HasJsonValueReaderWriter();
+
+ ///
+ public new virtual PropertyBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ => (PropertyBuilder)base.HasJsonValueReaderWriter(readerWriterType);
+
///
/// Adds or updates an annotation on the property. If an annotation with the key specified in
/// already exists its value will be updated.
diff --git a/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder.cs b/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder.cs
index 75ec81d72c5..7f9ff3e924e 100644
--- a/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder.cs
+++ b/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder.cs
@@ -3,6 +3,7 @@
using System.ComponentModel;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -158,6 +159,37 @@ public virtual TypeMappingConfigurationBuilder HasConversion(Type conversionType
return this;
}
+ ///
+ /// Configures the JSON reader/writer used by type mappings for this type.
+ ///
+ ///
+ /// Member-specific JSON reader/writer configuration takes precedence over this default. When a value converter
+ /// is used, the reader/writer must handle the converter's provider values.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual TypeMappingConfigurationBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => HasJsonValueReaderWriter(typeof(TReaderWriter));
+
+ ///
+ /// Configures the JSON reader/writer used by type mappings for this type.
+ ///
+ ///
+ /// Member-specific JSON reader/writer configuration takes precedence over this default. When a value converter
+ /// is used, the reader/writer must handle the converter's provider values.
+ /// To change the provider representation for server-side queries, configure a value converter as well.
+ ///
+ /// The JSON reader/writer type, or to clear the configuration.
+ /// The same builder instance so that multiple configuration calls can be chained.
+ public virtual TypeMappingConfigurationBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ {
+ Configuration.SetJsonValueReaderWriterType(readerWriterType);
+
+ return this;
+ }
+
#region Hidden System.Object members
///
diff --git a/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder`.cs b/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder`.cs
index 8423f5370fe..fa955dcf051 100644
--- a/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder`.cs
+++ b/src/EFCore/Metadata/Builders/TypeMappingConfigurationBuilder`.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Metadata.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -116,4 +117,13 @@ public virtual TypeMappingConfigurationBuilder HasSentinel(TProperty?
/// The same builder instance so that multiple configuration calls can be chained.
public new virtual TypeMappingConfigurationBuilder HasConversion(Type conversionType)
=> (TypeMappingConfigurationBuilder)base.HasConversion(conversionType);
+
+ ///
+ public new virtual TypeMappingConfigurationBuilder HasJsonValueReaderWriter()
+ where TReaderWriter : JsonValueReaderWriter
+ => (TypeMappingConfigurationBuilder)base.HasJsonValueReaderWriter();
+
+ ///
+ public new virtual TypeMappingConfigurationBuilder HasJsonValueReaderWriter(Type? readerWriterType)
+ => (TypeMappingConfigurationBuilder)base.HasJsonValueReaderWriter(readerWriterType);
}
diff --git a/src/EFCore/Metadata/Conventions/RuntimeModelConvention.cs b/src/EFCore/Metadata/Conventions/RuntimeModelConvention.cs
index ffd397ab072..7afc2691d9b 100644
--- a/src/EFCore/Metadata/Conventions/RuntimeModelConvention.cs
+++ b/src/EFCore/Metadata/Conventions/RuntimeModelConvention.cs
@@ -300,7 +300,8 @@ private static RuntimeTypeMappingConfiguration Create(ITypeMappingConfiguration
typeConfiguration.GetPrecision(),
typeConfiguration.GetScale(),
typeConfiguration.GetProviderClrType(),
- valueConverter);
+ valueConverter,
+ typeConfiguration.GetJsonValueReaderWriterType());
}
///
@@ -422,7 +423,7 @@ private static RuntimeElementType Create(RuntimeProperty runtimeProperty, IEleme
element.GetProviderClrType(),
element.GetValueConverter(),
element.GetValueComparer(),
- element.GetJsonValueReaderWriter(),
+ element[CoreAnnotationNames.JsonValueReaderWriterType] is not null ? element.GetJsonValueReaderWriter() : null,
element.GetTypeMapping());
///
diff --git a/src/EFCore/Metadata/ITypeMappingConfiguration.cs b/src/EFCore/Metadata/ITypeMappingConfiguration.cs
index 301bc7ef23d..400003117f4 100644
--- a/src/EFCore/Metadata/ITypeMappingConfiguration.cs
+++ b/src/EFCore/Metadata/ITypeMappingConfiguration.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Metadata.Internal;
+
namespace Microsoft.EntityFrameworkCore.Metadata;
///
@@ -54,4 +56,11 @@ public interface ITypeMappingConfiguration : IAnnotatable
///
/// The provider type, or if none has been set.
Type? GetProviderClrType();
+
+ ///
+ /// Gets the JSON reader/writer type configured for this type.
+ ///
+ /// The reader/writer type, or if none has been configured.
+ Type? GetJsonValueReaderWriterType()
+ => (Type?)this[CoreAnnotationNames.JsonValueReaderWriterType];
}
diff --git a/src/EFCore/Metadata/Internal/ElementType.cs b/src/EFCore/Metadata/Internal/ElementType.cs
index ed492b28bd1..836a934c4d7 100644
--- a/src/EFCore/Metadata/Internal/ElementType.cs
+++ b/src/EFCore/Metadata/Internal/ElementType.cs
@@ -19,6 +19,7 @@ public class ElementType : ConventionAnnotatable, IMutableElementType, IConventi
private bool? _isNullable;
private CoreTypeMapping? _typeMapping;
+ private JsonValueReaderWriter? _jsonValueReaderWriter;
private ConfigurationSource? _isNullableConfigurationSource;
private ConfigurationSource? _typeMappingConfigurationSource;
@@ -549,8 +550,14 @@ public virtual CoreTypeMapping? TypeMapping
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
public virtual JsonValueReaderWriter? GetJsonValueReaderWriter()
- => JsonValueReaderWriter.CreateFromType((Type?)this[CoreAnnotationNames.JsonValueReaderWriterType])
+ {
+ var readerWriter = _jsonValueReaderWriter
+ ?? JsonValueReaderWriter.CreateFromType((Type?)this[CoreAnnotationNames.JsonValueReaderWriterType]);
+ return (IsReadOnly && readerWriter != null
+ ? NonCapturingLazyInitializer.EnsureInitialized(ref _jsonValueReaderWriter, readerWriter)
+ : readerWriter)
?? TypeMapping?.JsonValueReaderWriter;
+ }
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore/Metadata/Internal/InternalElementTypeBuilder.cs b/src/EFCore/Metadata/Internal/InternalElementTypeBuilder.cs
index 511cf033a9b..331ab48ba5c 100644
--- a/src/EFCore/Metadata/Internal/InternalElementTypeBuilder.cs
+++ b/src/EFCore/Metadata/Internal/InternalElementTypeBuilder.cs
@@ -240,6 +240,34 @@ public virtual bool CanSetConversion(Type? providerClrType, ConfigurationSource?
|| Metadata.GetProviderClrType() == providerClrType)
&& configurationSource.Overrides(Metadata.GetValueConverterConfigurationSource());
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual InternalElementTypeBuilder? HasJsonValueReaderWriter(Type? readerWriterType, ConfigurationSource configurationSource)
+ {
+ if (!CanSetJsonValueReaderWriter(readerWriterType, configurationSource))
+ {
+ return null;
+ }
+
+ Metadata.SetJsonValueReaderWriterType(readerWriterType, configurationSource);
+
+ return this;
+ }
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual bool CanSetJsonValueReaderWriter(Type? readerWriterType, ConfigurationSource? configurationSource)
+ => configurationSource.Overrides(Metadata.GetJsonValueReaderWriterTypeConfigurationSource())
+ || (Type?)Metadata[CoreAnnotationNames.JsonValueReaderWriterType] == readerWriterType;
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
@@ -539,6 +567,26 @@ bool IConventionElementTypeBuilder.CanSetScale(int? scale, bool fromDataAnnotati
bool IConventionElementTypeBuilder.CanSetConversion(ValueConverter? converter, bool fromDataAnnotation)
=> CanSetConversion(converter, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ IConventionElementTypeBuilder? IConventionElementTypeBuilder.HasJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation)
+ => HasJsonValueReaderWriter(
+ readerWriterType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ bool IConventionElementTypeBuilder.CanSetJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation)
+ => CanSetJsonValueReaderWriter(
+ readerWriterType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
diff --git a/src/EFCore/Metadata/Internal/InternalPropertyBuilder.cs b/src/EFCore/Metadata/Internal/InternalPropertyBuilder.cs
index bc175bce209..7f730aaab21 100644
--- a/src/EFCore/Metadata/Internal/InternalPropertyBuilder.cs
+++ b/src/EFCore/Metadata/Internal/InternalPropertyBuilder.cs
@@ -600,6 +600,34 @@ public virtual bool CanSetConversion(Type? providerClrType, ConfigurationSource?
|| Metadata.GetElementType() == null
|| configurationSource.Overrides(Metadata.GetConfigurationSource()));
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual InternalPropertyBuilder? HasJsonValueReaderWriter(Type? readerWriterType, ConfigurationSource configurationSource)
+ {
+ if (!CanSetJsonValueReaderWriter(readerWriterType, configurationSource))
+ {
+ return null;
+ }
+
+ Metadata.SetJsonValueReaderWriterType(readerWriterType, configurationSource);
+
+ return this;
+ }
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual bool CanSetJsonValueReaderWriter(Type? readerWriterType, ConfigurationSource? configurationSource)
+ => configurationSource.Overrides(Metadata.GetJsonValueReaderWriterTypeConfigurationSource())
+ || (Type?)Metadata[CoreAnnotationNames.JsonValueReaderWriterType] == readerWriterType;
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
@@ -1441,6 +1469,26 @@ bool IConventionPropertyBuilder.CanSetValueGeneratorFactory(
bool IConventionPropertyBuilder.CanSetConversion(ValueConverter? converter, bool fromDataAnnotation)
=> CanSetConversion(converter, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ IConventionPropertyBuilder? IConventionPropertyBuilder.HasJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation)
+ => HasJsonValueReaderWriter(
+ readerWriterType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ bool IConventionPropertyBuilder.CanSetJsonValueReaderWriter(Type? readerWriterType, bool fromDataAnnotation)
+ => CanSetJsonValueReaderWriter(
+ readerWriterType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
diff --git a/src/EFCore/Metadata/Internal/Property.cs b/src/EFCore/Metadata/Internal/Property.cs
index 5daa69d580d..b78081b813d 100644
--- a/src/EFCore/Metadata/Internal/Property.cs
+++ b/src/EFCore/Metadata/Internal/Property.cs
@@ -26,6 +26,7 @@ public class Property : PropertyBase, IMutableProperty, IConventionProperty, IRu
private CoreTypeMapping? _typeMapping;
private ValueComparer? _valueComparer;
private ValueComparer? _keyValueComparer;
+ private JsonValueReaderWriter? _jsonValueReaderWriter;
private readonly ElementType? _elementType;
private ConfigurationSource? _typeConfigurationSource;
@@ -1371,7 +1372,13 @@ public virtual CoreTypeMapping? TypeMapping
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
public virtual JsonValueReaderWriter? GetJsonValueReaderWriter()
- => JsonValueReaderWriter.CreateFromType((Type?)this[CoreAnnotationNames.JsonValueReaderWriterType]);
+ {
+ var readerWriter = _jsonValueReaderWriter
+ ?? JsonValueReaderWriter.CreateFromType((Type?)this[CoreAnnotationNames.JsonValueReaderWriterType]);
+ return IsReadOnly && readerWriter != null
+ ? NonCapturingLazyInitializer.EnsureInitialized(ref _jsonValueReaderWriter, readerWriter)
+ : readerWriter;
+ }
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore/Metadata/Internal/PropertyConfiguration.cs b/src/EFCore/Metadata/Internal/PropertyConfiguration.cs
index fe10e4c30c0..cc56ef89af8 100644
--- a/src/EFCore/Metadata/Internal/PropertyConfiguration.cs
+++ b/src/EFCore/Metadata/Internal/PropertyConfiguration.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using Microsoft.EntityFrameworkCore.Storage.Json;
+
namespace Microsoft.EntityFrameworkCore.Metadata.Internal;
///
@@ -30,6 +32,32 @@ public PropertyConfiguration(Type clrType)
///
public virtual Type ClrType { get; }
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual Type? GetJsonValueReaderWriterType()
+ => (Type?)this[CoreAnnotationNames.JsonValueReaderWriterType];
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ public virtual void SetJsonValueReaderWriterType(Type? readerWriterType)
+ {
+ if (readerWriterType != null
+ && !readerWriterType.GetGenericTypeImplementations(typeof(JsonValueReaderWriter<>)).Any())
+ {
+ throw new InvalidOperationException(CoreStrings.BadJsonValueReaderWriterType(readerWriterType.ShortDisplayName()));
+ }
+
+ this[CoreAnnotationNames.JsonValueReaderWriterType] = readerWriterType;
+ }
+
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
diff --git a/src/EFCore/Metadata/RuntimeElementType.cs b/src/EFCore/Metadata/RuntimeElementType.cs
index 3ccbc731ea3..1735afbd37c 100644
--- a/src/EFCore/Metadata/RuntimeElementType.cs
+++ b/src/EFCore/Metadata/RuntimeElementType.cs
@@ -197,6 +197,9 @@ public virtual ValueComparer SetComparer(ValueComparer valueComparer)
///
public virtual JsonValueReaderWriter? GetJsonValueReaderWriter()
+ => _jsonValueReaderWriter ?? _typeMapping?.JsonValueReaderWriter;
+
+ internal JsonValueReaderWriter? ConfiguredJsonValueReaderWriter
=> _jsonValueReaderWriter;
///
diff --git a/src/EFCore/Metadata/RuntimeModel.cs b/src/EFCore/Metadata/RuntimeModel.cs
index 2ed9cacc2f0..3516c6df2fb 100644
--- a/src/EFCore/Metadata/RuntimeModel.cs
+++ b/src/EFCore/Metadata/RuntimeModel.cs
@@ -233,6 +233,7 @@ private IEnumerable GetEntityTypes()
/// The type that the property value will be converted to before being sent to the database provider.
///
/// The custom for this type.
+ /// The JSON reader/writer type for this type.
/// The newly created property.
public virtual RuntimeTypeMappingConfiguration AddTypeMappingConfiguration(
Type clrType,
@@ -241,7 +242,8 @@ public virtual RuntimeTypeMappingConfiguration AddTypeMappingConfiguration(
int? precision = null,
int? scale = null,
Type? providerPropertyType = null,
- ValueConverter? valueConverter = null)
+ ValueConverter? valueConverter = null,
+ Type? jsonValueReaderWriterType = null)
{
var typeConfiguration = new RuntimeTypeMappingConfiguration(
clrType,
@@ -250,7 +252,8 @@ public virtual RuntimeTypeMappingConfiguration AddTypeMappingConfiguration(
precision,
scale,
providerPropertyType,
- valueConverter);
+ valueConverter,
+ jsonValueReaderWriterType);
_typeConfigurations.Add(clrType, typeConfiguration);
diff --git a/src/EFCore/Metadata/RuntimeTypeMappingConfiguration.cs b/src/EFCore/Metadata/RuntimeTypeMappingConfiguration.cs
index 090d4699264..d0dda66933f 100644
--- a/src/EFCore/Metadata/RuntimeTypeMappingConfiguration.cs
+++ b/src/EFCore/Metadata/RuntimeTypeMappingConfiguration.cs
@@ -29,7 +29,8 @@ public RuntimeTypeMappingConfiguration(
int? precision,
int? scale,
Type? providerClrType,
- ValueConverter? valueConverter)
+ ValueConverter? valueConverter,
+ Type? jsonValueReaderWriterType = null)
{
ClrType = clrType;
@@ -59,6 +60,10 @@ public RuntimeTypeMappingConfiguration(
}
_valueConverter = valueConverter;
+ if (jsonValueReaderWriterType != null)
+ {
+ SetAnnotation(CoreAnnotationNames.JsonValueReaderWriterType, jsonValueReaderWriterType);
+ }
}
///
@@ -95,4 +100,9 @@ public RuntimeTypeMappingConfiguration(
[DebuggerStepThrough]
Type? ITypeMappingConfiguration.GetProviderClrType()
=> (Type?)this[CoreAnnotationNames.ProviderClrType];
+
+ ///
+ [DebuggerStepThrough]
+ Type? ITypeMappingConfiguration.GetJsonValueReaderWriterType()
+ => (Type?)this[CoreAnnotationNames.JsonValueReaderWriterType];
}
diff --git a/src/EFCore/Properties/CoreStrings.Designer.cs b/src/EFCore/Properties/CoreStrings.Designer.cs
index cdfad5bb371..7e4b4e2b5ac 100644
--- a/src/EFCore/Properties/CoreStrings.Designer.cs
+++ b/src/EFCore/Properties/CoreStrings.Designer.cs
@@ -26,6 +26,31 @@ public static class CoreStrings
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.EntityFrameworkCore.Properties.CoreStrings", typeof(CoreStrings).Assembly);
+ ///
+ /// A JSON reader/writer cannot be configured for the primitive collection '{structuralType}.{property}'. Configure a JSON reader/writer for its elements instead.
+ ///
+ public static string JsonValueReaderWriterOnPrimitiveCollection(object? structuralType, object? property)
+ => string.Format(
+ GetString("JsonValueReaderWriterOnPrimitiveCollection", nameof(structuralType), nameof(property)),
+ structuralType, property);
+
+ ///
+ /// The JSON reader/writer '{readerWriter}' is configured on '{structuralType}.{property}', but this member is not mapped to JSON. Map the member to JSON or remove its JSON reader/writer configuration.
+ ///
+ public static string JsonValueReaderWriterOnNonJsonProperty(object? structuralType, object? property, object? readerWriter)
+ => string.Format(
+ GetString("JsonValueReaderWriterOnNonJsonProperty", nameof(structuralType), nameof(property), nameof(readerWriter)),
+ structuralType, property, readerWriter);
+
+ ///
+ /// The JSON reader/writer '{readerWriter}' configured on '{structuralType}.{property}' reads and writes '{valueType}', but the member's store value type is '{storeType}'. Configure a reader/writer compatible with the store value type.
+ ///
+ public static string JsonValueReaderWriterPropertyMismatch(
+ object? structuralType, object? property, object? readerWriter, object? valueType, object? storeType)
+ => string.Format(
+ GetString("JsonValueReaderWriterPropertyMismatch", nameof(structuralType), nameof(property), nameof(readerWriter), nameof(valueType), nameof(storeType)),
+ structuralType, property, readerWriter, valueType, storeType);
+
///
/// The entity type '{entityType}' cannot be instantiated because its corresponding CLR type is abstract and there is no derived entity type in the model that corresponds to a concrete CLR type. Add a concrete derived entity type to the model or change the entity type to use a concrete CLR type.
///
diff --git a/src/EFCore/Properties/CoreStrings.resx b/src/EFCore/Properties/CoreStrings.resx
index 8a5b66d90b3..a3787cdd28c 100644
--- a/src/EFCore/Properties/CoreStrings.resx
+++ b/src/EFCore/Properties/CoreStrings.resx
@@ -117,6 +117,15 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+ A JSON reader/writer cannot be configured for the primitive collection '{structuralType}.{property}'. Configure a JSON reader/writer for its elements instead.
+
+
+ The JSON reader/writer '{readerWriter}' is configured on '{structuralType}.{property}', but this member is not mapped to JSON. Map the member to JSON or remove its JSON reader/writer configuration.
+
+
+ The JSON reader/writer '{readerWriter}' configured on '{structuralType}.{property}' reads and writes '{valueType}', but the member's store value type is '{storeType}'. Configure a reader/writer compatible with the store value type.
+
The entity type '{entityType}' cannot be instantiated because its corresponding CLR type is abstract and there is no derived entity type in the model that corresponds to a concrete CLR type. Add a concrete derived entity type to the model or change the entity type to use a concrete CLR type.
diff --git a/src/EFCore/Storage/CoreTypeMapping.cs b/src/EFCore/Storage/CoreTypeMapping.cs
index ebad3783b5a..fab1d3bda13 100644
--- a/src/EFCore/Storage/CoreTypeMapping.cs
+++ b/src/EFCore/Storage/CoreTypeMapping.cs
@@ -139,20 +139,12 @@ public CoreTypeMappingParameters WithComposedConverter(
return readerWriter;
}
- if (!RuntimeFeature.IsDynamicCodeSupported)
- {
- throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel);
- }
-
if (readerWriter is IJsonConvertedValueReaderWriter convertedValueReaderWriter)
{
readerWriter = convertedValueReaderWriter.InnerReaderWriter;
}
- return (JsonValueReaderWriter)Activator.CreateInstance(
- typeof(JsonConvertedValueReaderWriter<,>).MakeGenericType(
- converter.ModelClrType, readerWriter.ValueType),
- readerWriter, converter)!;
+ return CreateJsonValueReaderWriter(converter, readerWriter);
}
}
}
@@ -327,6 +319,42 @@ public abstract CoreTypeMapping WithComposedConverter(
CoreTypeMapping? elementMapping = null,
JsonValueReaderWriter? jsonValueReaderWriter = null);
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ [EntityFrameworkInternal]
+ public virtual CoreTypeMapping WithJsonValueReaderWriter(JsonValueReaderWriter jsonValueReaderWriter)
+ {
+ if (ReferenceEquals(JsonValueReaderWriter, jsonValueReaderWriter)
+ && jsonValueReaderWriter.ValueType.IsAssignableFrom(ClrType))
+ {
+ return this;
+ }
+
+ return Clone(
+ Parameters with
+ {
+ JsonValueReaderWriter = Converter is { } converter
+ ? CreateJsonValueReaderWriter(converter, jsonValueReaderWriter)
+ : jsonValueReaderWriter
+ });
+ }
+
+ private static JsonValueReaderWriter CreateJsonValueReaderWriter(ValueConverter converter, JsonValueReaderWriter readerWriter)
+ {
+ if (!RuntimeFeature.IsDynamicCodeSupported)
+ {
+ throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel);
+ }
+
+ return (JsonValueReaderWriter)Activator.CreateInstance(
+ typeof(JsonConvertedValueReaderWriter<,>).MakeGenericType(converter.ModelClrType, readerWriter.ValueType),
+ readerWriter, converter)!;
+ }
+
///
/// Clones the type mapping to update any parameter if needed.
///
diff --git a/src/EFCore/Storage/Json/JsonValueReaderWriter.cs b/src/EFCore/Storage/Json/JsonValueReaderWriter.cs
index bcae4ed0b75..47d6d140578 100644
--- a/src/EFCore/Storage/Json/JsonValueReaderWriter.cs
+++ b/src/EFCore/Storage/Json/JsonValueReaderWriter.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
@@ -10,10 +11,20 @@ namespace Microsoft.EntityFrameworkCore.Storage.Json;
/// Reads and writes the JSON value for a given model or provider value.
///
///
-/// Implementations of this type must inherit from the generic
+///
+/// Implementations of this type must inherit from the generic .
+///
+///
+/// A reader/writer formats values without changing their meaning. Changes to a value or its storage type must be
+/// expressed using a value converter, with the reader/writer handling the converter's provider values. The formatter
+/// must preserve the value read by the provider's normal scalar materialization. This cannot be validated; an
+/// incompatible formatter can cause failures at runtime.
+///
///
public abstract class JsonValueReaderWriter
{
+ private static readonly ConditionalWeakTable Instances = new();
+
///
/// Ensures the external types extend from the generic
///
@@ -88,15 +99,25 @@ public object FromJsonString(string json, object? existingObject = null)
/// The value to write.
/// The JSON representation of the given value.
public string ToJsonString(object? value)
+ => Encoding.UTF8.GetString(ToJsonBytes(value).Span);
+
+ ///
+ /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
+ /// the same compatibility standards as public APIs. It may be changed or removed without notice in
+ /// 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.
+ ///
+ [EntityFrameworkInternal]
+ public virtual ReadOnlyMemory ToJsonBytes(object? value, JsonWriterOptions options = default)
{
using var stream = new MemoryStream();
- using var writer = new Utf8JsonWriter(stream);
+ using var writer = new Utf8JsonWriter(stream, options);
ToJson(writer, value);
writer.Flush();
- return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
+ return stream.GetBuffer().AsMemory(0, (int)stream.Length);
}
///
@@ -130,39 +151,42 @@ public virtual string ToJsonObjectString(string propertyName, object? value)
}
///
- /// Creates a instance of the given type, using the Instance
- /// property to get th singleton instance if possible.
+ /// Gets or creates a cached instance of the given type, using the Instance
+ /// property to get the singleton instance if possible.
///
+ ///
+ /// Reader/writer instances are shared and must be thread-safe.
+ ///
/// The type, which must inherit from .
- /// The reader/writer instance./
+ /// The reader/writer instance.
///
/// if the type does not represent a
/// that can be instantiated.
///
public static JsonValueReaderWriter? CreateFromType(Type? readerWriterType)
- {
- if (readerWriterType != null)
- {
- var instanceProperty = readerWriterType.GetAnyProperty("Instance");
- try
- {
- return instanceProperty != null
- && instanceProperty.IsStatic()
- && instanceProperty.GetMethod?.IsPublic == true
- && readerWriterType.IsAssignableFrom(instanceProperty.PropertyType)
- ? (JsonValueReaderWriter?)instanceProperty.GetValue(null)
- : (JsonValueReaderWriter?)Activator.CreateInstance(readerWriterType);
- }
- catch (Exception e)
- {
- throw new InvalidOperationException(
- CoreStrings.CannotCreateJsonValueReaderWriter(
- readerWriterType.ShortDisplayName()), e);
- }
- }
-
- return null;
- }
+ => readerWriterType == null
+ ? null
+ : Instances.GetValue(
+ readerWriterType,
+ static type =>
+ {
+ var instanceProperty = type.GetAnyProperty("Instance");
+ try
+ {
+ return instanceProperty != null
+ && instanceProperty.IsStatic()
+ && instanceProperty.GetMethod?.IsPublic == true
+ && type.IsAssignableFrom(instanceProperty.PropertyType)
+ ? (JsonValueReaderWriter?)instanceProperty.GetValue(null)
+ : (JsonValueReaderWriter?)Activator.CreateInstance(type);
+ }
+ catch (Exception e)
+ {
+ throw new InvalidOperationException(
+ CoreStrings.CannotCreateJsonValueReaderWriter(
+ type.ShortDisplayName()), e);
+ }
+ });
///
/// The expression representing construction of this object.
diff --git a/src/EFCore/Storage/TypeMappingInfo.cs b/src/EFCore/Storage/TypeMappingInfo.cs
index 0d2fc8c5968..8925cbf71d1 100644
--- a/src/EFCore/Storage/TypeMappingInfo.cs
+++ b/src/EFCore/Storage/TypeMappingInfo.cs
@@ -102,7 +102,17 @@ public TypeMappingInfo(
ClrType = (customConverter?.ProviderClrType ?? elementType.ClrType).UnwrapNullableType();
Scale = fallbackScale ?? mappingHints?.Scale;
Precision = fallbackPrecision ?? mappingHints?.Precision;
- JsonValueReaderWriter = JsonValueReaderWriter.CreateFromType((Type?)elementType[CoreAnnotationNames.JsonValueReaderWriterType]);
+
+ // The public getter can resolve or reuse a type mapping. Read only configured readers here
+ // to avoid recursive mapping resolution and stale defaults.
+ JsonValueReaderWriter = elementType switch
+ {
+ RuntimeElementType runtimeElementType => runtimeElementType.ConfiguredJsonValueReaderWriter,
+ _ when elementType[CoreAnnotationNames.JsonValueReaderWriterType] != null => elementType.GetJsonValueReaderWriter(),
+ _ => null
+ };
+ JsonValueReaderWriter ??= GetJsonValueReaderWriter(
+ elementType.CollectionProperty.DeclaringType.Model.FindTypeMappingConfiguration(elementType.ClrType.UnwrapNullableType()));
}
///
@@ -200,7 +210,9 @@ public TypeMappingInfo(
ClrType = (customConverter?.ProviderClrType ?? property.ClrType).UnwrapNullableType();
Scale = fallbackScale ?? mappingHints?.Scale;
Precision = fallbackPrecision ?? mappingHints?.Precision;
- JsonValueReaderWriter = property.GetJsonValueReaderWriter();
+ JsonValueReaderWriter = property.GetJsonValueReaderWriter()
+ ?? GetJsonValueReaderWriter(
+ property.DeclaringType.Model.FindTypeMappingConfiguration(property.ClrType.UnwrapNullableType()));
}
///
@@ -245,6 +257,7 @@ public TypeMappingInfo(
precision: typeMappingConfiguration.GetPrecision(),
scale: typeMappingConfiguration.GetScale())
{
+ JsonValueReaderWriter = GetJsonValueReaderWriter(typeMappingConfiguration);
}
///
@@ -374,4 +387,7 @@ public TypeMappingInfo WithConverter(in ValueConverterInfo converterInfo)
/// The JSON reader/writer, if one has been provided, or otherwise.
///
public JsonValueReaderWriter? JsonValueReaderWriter { get; init; }
+
+ private static JsonValueReaderWriter? GetJsonValueReaderWriter(ITypeMappingConfiguration? configuration)
+ => JsonValueReaderWriter.CreateFromType(configuration?.GetJsonValueReaderWriterType());
}
diff --git a/src/EFCore/Storage/TypeMappingSource.cs b/src/EFCore/Storage/TypeMappingSource.cs
index 934359f1272..e1fe1a3adf3 100644
--- a/src/EFCore/Storage/TypeMappingSource.cs
+++ b/src/EFCore/Storage/TypeMappingSource.cs
@@ -48,6 +48,12 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
ValueConverter? customConverter = null;
if (principals != null)
{
+ mappingInfo = mappingInfo with
+ {
+ ElementTypeMapping = mappingInfo.ElementTypeMapping
+ ?? FindElementMapping(mappingInfo, principals[0].DeclaringType.Model)
+ };
+
for (var i = 0; i < principals.Count; i++)
{
var principal = principals[i];
@@ -129,9 +135,7 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
if (mapping != null)
{
- mapping = mapping.WithComposedConverter(
- secondConverterInfo.Create(),
- jsonValueReaderWriter: mappingInfoUsed.JsonValueReaderWriter);
+ mapping = mapping.WithComposedConverter(secondConverterInfo.Create());
break;
}
}
@@ -139,9 +143,7 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
if (mapping != null)
{
- mapping = mapping.WithComposedConverter(
- converterInfo.Create(),
- jsonValueReaderWriter: mappingInfo.JsonValueReaderWriter);
+ mapping = mapping.WithComposedConverter(converterInfo.Create());
break;
}
}
@@ -152,9 +154,17 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
if (mapping != null
&& customConverter != null)
{
- mapping = mapping.WithComposedConverter(
- customConverter,
- jsonValueReaderWriter: mappingInfo.JsonValueReaderWriter);
+ mapping = mapping.WithComposedConverter(customConverter);
+ }
+
+ if (mapping != null
+ && mappingInfo.JsonValueReaderWriter != null)
+ {
+ var readerWriter = mappingInfo.JsonValueReaderWriter;
+ mapping = mapping.Converter is { } converter
+ && !readerWriter.ValueType.UnwrapNullableType().IsAssignableFrom(converter.ProviderClrType.UnwrapNullableType())
+ ? mapping.Clone(jsonValueReaderWriter: readerWriter)
+ : mapping.WithJsonValueReaderWriter(readerWriter);
}
return mapping;
@@ -215,8 +225,13 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
/// The type mapping, or if none was found.
public override CoreTypeMapping? FindMapping(IElementType elementType)
{
+ var mappingInfo = new TypeMappingInfo(elementType);
+ mappingInfo = mappingInfo with
+ {
+ ElementTypeMapping = FindElementMapping(mappingInfo, elementType.CollectionProperty.DeclaringType.Model)
+ };
var resolvedMapping = FindMappingWithConversion(
- new TypeMappingInfo(elementType),
+ mappingInfo,
providerClrType: elementType.GetProviderClrType(),
customConverter: elementType.GetValueConverter());
@@ -261,12 +276,22 @@ protected TypeMappingSource(TypeMappingSourceDependencies dependencies)
if (typeConfiguration != null)
{
var mappingInfo = new TypeMappingInfo(type, typeConfiguration, elementMapping);
+ mappingInfo = mappingInfo with
+ {
+ // An inferred element mapping defines collection parameter transport, not document formatting.
+ JsonValueReaderWriter = elementMapping == null ? mappingInfo.JsonValueReaderWriter : null,
+ ElementTypeMapping = elementMapping ?? FindElementMapping(mappingInfo, model)
+ };
var providerClrType = typeConfiguration.GetProviderClrType()?.UnwrapNullableType();
return FindMappingWithConversion(mappingInfo, providerClrType, customConverter: typeConfiguration.GetValueConverter());
}
+ var defaultMappingInfo = new TypeMappingInfo(type, elementMapping);
return FindMappingWithConversion(
- new TypeMappingInfo(type, elementMapping),
+ defaultMappingInfo with
+ {
+ ElementTypeMapping = elementMapping ?? FindElementMapping(defaultMappingInfo, model)
+ },
providerClrType: null,
customConverter: null);
}
diff --git a/src/EFCore/Storage/TypeMappingSourceBase.cs b/src/EFCore/Storage/TypeMappingSourceBase.cs
index c7dd7e5a72f..56b0c673426 100644
--- a/src/EFCore/Storage/TypeMappingSourceBase.cs
+++ b/src/EFCore/Storage/TypeMappingSourceBase.cs
@@ -130,6 +130,26 @@ protected virtual void ValidateMapping(
public virtual CoreTypeMapping? FindMapping(MemberInfo member, IModel model, bool useAttributes)
=> FindMapping(member);
+ ///
+ /// Finds a model-aware element mapping for a collection type when element metadata is not available.
+ ///
+ /// The mapping info for the collection.
+ /// The model containing type mapping defaults.
+ /// The element mapping, or if the type is not a supported collection.
+ protected virtual CoreTypeMapping? FindElementMapping(TypeMappingInfo mappingInfo, IModel model)
+ => mappingInfo.ClrType is { } type
+ // These are scalar values even though they implement IEnumerable.
+ && type != typeof(string)
+ && type != typeof(byte[])
+ // Dictionary values need provider-specific mappings, not mappings for KeyValuePair.
+ && !type.GetGenericTypeImplementations(typeof(IDictionary<,>)).Any()
+ && !type.GetGenericTypeImplementations(typeof(IReadOnlyDictionary<,>)).Any()
+ && type.TryGetElementType(typeof(IEnumerable<>)) is { } elementType
+ // Avoid recursively resolving a sequence whose element type is the sequence itself.
+ && elementType != type
+ ? FindMapping(elementType, model)
+ : null;
+
///
/// Attempts to find a JSON-based type mapping for a collection of primitive types.
///
@@ -152,7 +172,8 @@ protected virtual bool TryFindJsonCollectionMapping(
&& modelClrType != typeof(string)
&& modelClrType.TryGetElementType(typeof(IEnumerable<>)) is { } elementType
&& elementType != modelClrType
- && !modelClrType.GetGenericTypeImplementations(typeof(IDictionary<,>)).Any())
+ && !modelClrType.GetGenericTypeImplementations(typeof(IDictionary<,>)).Any()
+ && !modelClrType.GetGenericTypeImplementations(typeof(IReadOnlyDictionary<,>)).Any())
{
elementMapping ??= FindMapping(elementType);
diff --git a/test/EFCore.Cosmos.FunctionalTests/AdHocVectorSearchCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/AdHocVectorSearchCosmosTest.cs
index 6371fde621f..7456fbc1ada 100644
--- a/test/EFCore.Cosmos.FunctionalTests/AdHocVectorSearchCosmosTest.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/AdHocVectorSearchCosmosTest.cs
@@ -1,8 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Text.Json;
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore;
@@ -15,6 +17,65 @@ protected override string NonSharedStoreName
protected override ITestStoreFactory NonSharedTestStoreFactory
=> CosmosTestStoreFactory.Instance;
+ [ConditionalFact(typeof(CosmosTestEnvironment), nameof(CosmosTestEnvironment.IsNotLinuxEmulator))]
+ public async Task Vector_parameters_use_the_configured_JSON_writer()
+ {
+ var factory = await InitializeNonSharedTest(
+ onModelCreating: b =>
+ {
+ b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ b.Entity().HasPartitionKey(e => e.Partition);
+ b.Entity().Property(e => e.Vector)
+ .IsVectorProperty(DistanceFunction.Euclidean, 3)
+ .HasJsonValueReaderWriter();
+ b.Entity().Property(e => e.MemoryVector)
+ .IsVectorProperty(DistanceFunction.Euclidean, 3)
+ .HasJsonValueReaderWriter();
+ },
+ seed: context =>
+ {
+ context.Add(new FormattedVectorItem { Id = 1, Partition = "p", Vector = [1, 2, 3], MemoryVector = new float[] { 1, 2, 3 } });
+ return context.SaveChangesAsync();
+ });
+ await using var context = factory.CreateDbContext();
+ var vector = new float[] { 1, 2, 3 };
+ var memory = new ReadOnlyMemory(vector);
+
+ Assert.Equal(
+ 0,
+ await context.Set()
+ .Select(e => EF.Functions.VectorDistance(e.Vector, vector, useBruteForce: true)).SingleAsync());
+ Assert.Equal(
+ 0,
+ await context.Set()
+ .Select(e => EF.Functions.VectorDistance(e.MemoryVector, memory, useBruteForce: true)).SingleAsync());
+ var item = await context.Set().SingleAsync();
+ Assert.Equal(vector, item.Vector);
+ Assert.Equal(vector, item.MemoryVector.ToArray());
+ }
+
+ private sealed class FormattedVectorItem
+ {
+ public int Id { get; set; }
+ public string Partition { get; set; } = null!;
+ public float[] Vector { get; set; } = [];
+ public ReadOnlyMemory MemoryVector { get; set; }
+ }
+
+ public sealed class ScaledVectorReaderWriter : JsonValueReaderWriter
+ {
+ private static readonly JsonCollectionOfStructsReaderWriter ReaderWriter = new(JsonFloatReaderWriter.Instance);
+
+ public override float[] FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => ((float[])ReaderWriter.FromJsonTyped(ref manager, existingObject)).Select(v => v / 10).ToArray();
+
+ public override void ToJsonTyped(Utf8JsonWriter writer, float[] value)
+ => ReaderWriter.ToJsonTyped(writer, value.Select(v => v * 10).ToArray());
+
+ public override Expression ConstructorExpression
+ => Expression.New(typeof(ScaledVectorReaderWriter));
+ }
+
#region CompositeVectorIndex
[Fact]
diff --git a/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs
index 69064b6ce04..bab88e03c1f 100644
--- a/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs
@@ -256,38 +256,6 @@ public override Task Can_read_write_polygon_typed_as_geometry()
// No built-in JSON support for spatial types in the Cosmos provider
=> Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_geometry);
- public override Task Can_read_write_point_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_point_as_GeoJson);
-
- public override Task Can_read_write_point_with_Z_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_point_with_Z_as_GeoJson);
-
- public override Task Can_read_write_point_with_M_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_point_with_M_as_GeoJson);
-
- public override Task Can_read_write_point_with_Z_and_M_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_point_with_Z_and_M_as_GeoJson);
-
- public override Task Can_read_write_line_string_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_line_string_as_GeoJson);
-
- public override Task Can_read_write_multi_line_string_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_multi_line_string_as_GeoJson);
-
- public override Task Can_read_write_polygon_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_polygon_as_GeoJson);
-
- public override Task Can_read_write_polygon_typed_as_geometry_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_geometry_as_GeoJson);
-
public override Task Can_read_write_nullable_point()
// No built-in JSON support for spatial types in the Cosmos provider
=> Assert.ThrowsAsync(base.Can_read_write_point);
@@ -304,30 +272,10 @@ public override Task Can_read_write_nullable_polygon()
// No built-in JSON support for spatial types in the Cosmos provider
=> Assert.ThrowsAsync(base.Can_read_write_polygon);
- public override Task Can_read_write_nullable_point_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_point_as_GeoJson);
-
- public override Task Can_read_write_nullable_line_string_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_line_string_as_GeoJson);
-
- public override Task Can_read_write_nullable_multi_line_string_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_multi_line_string_as_GeoJson);
-
- public override Task Can_read_write_nullable_polygon_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_polygon_as_GeoJson);
-
public override Task Can_read_write_polygon_typed_as_nullable_geometry()
// No built-in JSON support for spatial types in the Cosmos provider
=> Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_nullable_geometry);
- public override Task Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson()
- // No built-in JSON support for spatial types in the Cosmos provider
- => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson);
-
protected override ITestStoreFactory NonSharedTestStoreFactory
=> CosmosTestStoreFactory.Instance;
}
diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/AdHocMiscellaneousQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/AdHocMiscellaneousQueryCosmosTest.cs
index 85a1708ccfb..86218f859b6 100644
--- a/test/EFCore.Cosmos.FunctionalTests/Query/AdHocMiscellaneousQueryCosmosTest.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/Query/AdHocMiscellaneousQueryCosmosTest.cs
@@ -2,7 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel.DataAnnotations.Schema;
+using System.Globalization;
+using System.Text.Json;
using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal;
+using Microsoft.EntityFrameworkCore.Storage.Json;
namespace Microsoft.EntityFrameworkCore.Query;
@@ -417,6 +420,858 @@ public class Item
#endregion 39113
+ #region 31316
+
+ [Theory]
+ [InlineData(DateTimeKind.Utc)]
+ [InlineData(DateTimeKind.Unspecified)]
+ public virtual async Task Legacy_datetime_format_is_used_for_server_comparisons(DateTimeKind kind)
+ {
+ var timestamps = new[]
+ {
+ new DateTime(2026, 1, 1, 0, 0, 0, kind),
+ new DateTime(2026, 1, 1, 0, 0, 0, 123, kind),
+ new DateTime(2026, 1, 1, 0, 0, 0, 999, kind),
+ new DateTime(2026, 1, 1, 0, 0, 1, kind),
+ new DateTime(2026, 1, 2, 0, 0, 0, kind)
+ };
+ var contextFactory = await InitializeNonSharedTest(
+ onConfiguring: options => options.EnableSensitiveDataLogging(),
+ seed: async context =>
+ {
+ for (var i = 0; i < timestamps.Length; i++)
+ {
+ context.Items.Add(
+ new LegacyDateTimeContext.Item
+ {
+ Id = i + 1,
+ Timestamp = timestamps[i],
+ OptionalTimestamp = i == 2 ? null : timestamps[i],
+ Timestamps = [timestamps[i]],
+ DefaultTimestamp = timestamps[i]
+ });
+ }
+
+ await context.SaveChangesAsync();
+ });
+
+ await using var context = contextFactory.CreateDbContext();
+ var suffix = kind == DateTimeKind.Utc ? "Z" : "";
+ var container = context.Database.GetCosmosClient().GetContainer(
+ context.Database.GetCosmosDatabaseId(), "Entities");
+
+ for (var i = 0; i < 2; i++)
+ {
+ using var response = await container.ReadItemStreamAsync(
+ (i + 1).ToString(CultureInfo.InvariantCulture), Azure.Cosmos.PartitionKey.None);
+ response.EnsureSuccessStatusCode();
+ using var document = await JsonDocument.ParseAsync(response.Content);
+ var expected = i == 0 ? $"2026-01-01T00:00:00.000{suffix}" : $"2026-01-01T00:00:00.123{suffix}";
+ var expectedDefault = i == 0 ? $"2026-01-01T00:00:00.0000000{suffix}" : $"2026-01-01T00:00:00.1230000{suffix}";
+
+ Assert.Equal(expected, document.RootElement.GetProperty("Timestamp").GetString());
+ Assert.Equal(expected, document.RootElement.GetProperty("OptionalTimestamp").GetString());
+ Assert.Equal(expected, document.RootElement.GetProperty("Timestamps")[0].GetString());
+ Assert.Equal(expectedDefault, document.RootElement.GetProperty("DefaultTimestamp").GetString());
+ }
+
+ var boundary = timestamps[1];
+ var upper = timestamps[3];
+
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.Timestamp == boundary).Select(x => x.Id).ToArrayAsync());
+
+ var constantQuery = kind == DateTimeKind.Utc
+ ? context.Items.Where(x => x.Timestamp == new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Utc))
+ : context.Items.Where(x => x.Timestamp == new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Unspecified));
+ Assert.Equal(new[] { 2 }, await constantQuery.Select(x => x.Id).ToArrayAsync());
+
+ Assert.Equal(
+ new[] { 1 },
+ await context.Items.Where(x => x.Timestamp < boundary).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 4, 5 },
+ (await context.Items.Where(x => x.Timestamp >= upper).Select(x => x.Id).ToArrayAsync()).Order().ToArray());
+ Assert.Equal(
+ new[] { 2, 3 },
+ (await context.Items.Where(x => x.Timestamp >= boundary && x.Timestamp < upper).Select(x => x.Id).ToArrayAsync())
+ .Order().ToArray());
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.OptionalTimestamp == boundary).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 3 },
+ await context.Items.Where(x => x.OptionalTimestamp == null).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.Timestamps.Contains(boundary)).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.DefaultTimestamp == boundary).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.Timestamp == boundary && x.DefaultTimestamp == boundary).Select(x => x.Id).ToArrayAsync());
+ Assert.Equal(
+ new[] { 2 },
+ await context.Items.Where(x => x.DefaultTimestamp == boundary && x.Timestamp == boundary).Select(x => x.Id).ToArrayAsync());
+
+ var constantRangeQuery = kind == DateTimeKind.Utc
+ ? context.Items.Where(x => x.Timestamp >= new DateTime(2026, 1, 1, 0, 0, 1, DateTimeKind.Utc))
+ : context.Items.Where(x => x.Timestamp >= new DateTime(2026, 1, 1, 0, 0, 1, DateTimeKind.Unspecified));
+ Assert.Equal(
+ new[] { 4, 5 },
+ (await constantRangeQuery.Select(x => x.Id).ToArrayAsync()).Order().ToArray());
+
+ var items = (await context.Items.ToListAsync()).OrderBy(x => x.Id).ToArray();
+ Assert.Equal([1, 2, 3, 4, 5], items.Select(x => x.Id).ToArray());
+ for (var i = 0; i < items.Length; i++)
+ {
+ Assert.Equal(timestamps[i], items[i].Timestamp);
+ Assert.Equal(kind, items[i].Timestamp.Kind);
+ Assert.Equal(i == 2 ? (DateTime?)null : timestamps[i], items[i].OptionalTimestamp);
+ Assert.Equal([timestamps[i]], items[i].Timestamps);
+ Assert.Equal(kind, items[i].Timestamps[0].Kind);
+ Assert.Equal(timestamps[i], items[i].DefaultTimestamp);
+ }
+
+ AssertSql(
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] = @boundary)
+""",
+ //
+ $"""
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] = "2026-01-01T00:00:00.123{suffix}")
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] < @boundary)
+""",
+ //
+ $"""
+@upper='2026-01-01T00:00:01.000{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] >= @upper)
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+@upper='2026-01-01T00:00:01.000{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ((c["Timestamp"] >= @boundary) AND (c["Timestamp"] < @upper))
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["OptionalTimestamp"] = @boundary)
+""",
+ //
+ """
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["OptionalTimestamp"] = null)
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ARRAY_CONTAINS(c["Timestamps"], @boundary)
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.1230000{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["DefaultTimestamp"] = @boundary)
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.123{suffix}'
+@boundary0='2026-01-01T00:00:00.1230000{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ((c["Timestamp"] = @boundary) AND (c["DefaultTimestamp"] = @boundary0))
+""",
+ //
+ $"""
+@boundary='2026-01-01T00:00:00.1230000{suffix}'
+@boundary0='2026-01-01T00:00:00.123{suffix}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ((c["DefaultTimestamp"] = @boundary) AND (c["Timestamp"] = @boundary0))
+""",
+ //
+ $"""
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] >= "2026-01-01T00:00:01.000{suffix}")
+""",
+ //
+ """
+SELECT VALUE c
+FROM root c
+""");
+ }
+
+ [Theory, InlineData(false), InlineData(true)]
+ public async Task Contains_uses_collection_element_reader_writer_override(bool legacyDefault)
+ {
+ var timestamp = new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Utc);
+ var factory = await InitializeNonSharedTest(
+ onConfiguring: options => options.EnableSensitiveDataLogging(),
+ onModelCreating: b =>
+ {
+ var entity = b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ entity.PrimitiveCollection(e => e.Timestamps).ElementType().HasJsonValueReaderWriter(
+ legacyDefault ? typeof(JsonDateTimeReaderWriter) : typeof(LegacyDateTimeJsonReaderWriter));
+ },
+ configureConventions: c => c.DefaultTypeMapping().HasJsonValueReaderWriter(
+ legacyDefault ? typeof(LegacyDateTimeJsonReaderWriter) : typeof(JsonDateTimeReaderWriter)),
+ seed: async context =>
+ {
+ context.Add(new LegacyDateTimeContext.Item { Id = 1, Timestamps = [timestamp] });
+ await context.SaveChangesAsync();
+ });
+ await using var context = factory.CreateDbContext();
+ TestSqlLoggerFactory.Clear();
+ Assert.Equal(
+ new[] { 1 },
+ await context.Set().Where(e => e.Timestamps.Contains(timestamp)).Select(e => e.Id).ToArrayAsync());
+ var expectedTimestamp = legacyDefault ? "2026-01-01T00:00:00.1230000Z" : "2026-01-01T00:00:00.123Z";
+ AssertSql(
+ $"""
+@timestamp='{expectedTimestamp}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ARRAY_CONTAINS(c["Timestamps"], @timestamp)
+""");
+ }
+
+ [Theory]
+ [InlineData(false, false, false)]
+ [InlineData(false, true, false)]
+ [InlineData(true, false, false)]
+ [InlineData(true, true, false)]
+ [InlineData(false, false, true)]
+ [InlineData(false, true, true)]
+ [InlineData(true, false, true)]
+ [InlineData(true, true, true)]
+ public async Task Contains_uses_property_reader_writer(bool legacyDefault, bool memberOverride, bool collectionDefault)
+ {
+ var timestamp = new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Utc);
+ var legacyMember = memberOverride ? !legacyDefault : legacyDefault;
+ var factory = await InitializeNonSharedTest(
+ onConfiguring: options => options.EnableSensitiveDataLogging(),
+ configureConventions: c =>
+ {
+ c.DefaultTypeMapping().HasJsonValueReaderWriter(
+ legacyDefault ? typeof(LegacyDateTimeJsonReaderWriter) : typeof(JsonDateTimeReaderWriter));
+ if (collectionDefault)
+ {
+ c.DefaultTypeMapping().HasJsonValueReaderWriter();
+ }
+ },
+ onModelCreating: b =>
+ {
+ var entity = b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ if (memberOverride)
+ {
+ entity.Property(e => e.Timestamp).HasJsonValueReaderWriter(
+ legacyMember ? typeof(LegacyDateTimeJsonReaderWriter) : typeof(JsonDateTimeReaderWriter));
+ }
+ },
+ seed: async context =>
+ {
+ context.Add(new LegacyDateTimeContext.Item { Id = 1, Timestamp = timestamp });
+ await context.SaveChangesAsync();
+ });
+ await using var context = factory.CreateDbContext();
+ TestSqlLoggerFactory.Clear();
+ Assert.Equal(
+ new[] { 1 },
+ await context.Set()
+ .Where(e => new[] { e.Timestamp }.AsQueryable().Contains(timestamp))
+ .Select(e => e.Id).ToArrayAsync());
+ var timestamps = new[] { timestamp };
+ Assert.Equal(
+ new[] { 1 },
+ await context.Set()
+ .Where(e => EF.Parameter(timestamps).AsQueryable().Contains(e.Timestamp))
+ .Select(e => e.Id).ToArrayAsync());
+ foreach (var singleValue in new[] { true, false })
+ {
+ var inlineQuery = singleValue
+ ? context.Set()
+ .Where(e => new[] { new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Utc) }.AsQueryable().Contains(e.Timestamp))
+ : context.Set()
+ .Where(e => new[]
+ {
+ new DateTime(2026, 1, 1, 0, 0, 0, 123, DateTimeKind.Utc),
+ new DateTime(2026, 1, 2, 0, 0, 0, 123, DateTimeKind.Utc)
+ }.AsQueryable().Contains(e.Timestamp));
+ Assert.Equal(
+ new[] { 1 },
+ await inlineQuery.Select(e => e.Id).ToArrayAsync());
+ }
+ var expectedTimestamp = legacyMember ? "2026-01-01T00:00:00.123Z" : "2026-01-01T00:00:00.1230000Z";
+ AssertSql(
+ $"""
+@timestamp='{expectedTimestamp}'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (@timestamp = c["Timestamp"])
+""",
+ //
+ $"""
+@timestamps='["{expectedTimestamp}"]'
+
+SELECT VALUE c["Id"]
+FROM root c
+WHERE ARRAY_CONTAINS(@timestamps, c["Timestamp"])
+""",
+ $"""
+SELECT VALUE c["Id"]
+FROM root c
+WHERE (c["Timestamp"] = "{expectedTimestamp}")
+""",
+ $"""
+SELECT VALUE c["Id"]
+FROM root c
+WHERE c["Timestamp"] IN ("{expectedTimestamp}", "{(legacyMember ? "2026-01-02T00:00:00.123Z" : "2026-01-02T00:00:00.1230000Z")}")
+""");
+ }
+
+ protected class LegacyDateTimeContext(DbContextOptions options) : DbContext(options)
+ {
+ public DbSet- Items
+ => Set
- ();
+
+ protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
+ => configurationBuilder.DefaultTypeMapping()
+ .HasJsonValueReaderWriter();
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ modelBuilder.Entity
- ().ToContainer("Entities").HasNoDiscriminator();
+ modelBuilder.Entity
- ().Property(x => x.DefaultTimestamp)
+ .HasJsonValueReaderWriter();
+ }
+
+ public class Item
+ {
+ public int Id { get; set; }
+ public DateTime Timestamp { get; set; }
+ public DateTime? OptionalTimestamp { get; set; }
+ public List Timestamps { get; set; } = [];
+ public DateTime DefaultTimestamp { get; set; }
+ }
+ }
+
+ public sealed class LegacyDateTimeJsonReaderWriter : JsonValueReaderWriter
+ {
+ private static readonly JsonDateTimeReaderWriter ReaderWriter = new("yyyy-MM-dd'T'HH:mm:ss.fffK");
+
+ public static LegacyDateTimeJsonReaderWriter Instance { get; } = new();
+
+ public override DateTime FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => ReaderWriter.FromJsonTyped(ref manager, existingObject);
+
+ public override void ToJsonTyped(Utf8JsonWriter writer, DateTime value)
+ => ReaderWriter.ToJsonTyped(writer, value);
+
+ public override Expression ConstructorExpression
+ => Expression.Property(null, typeof(LegacyDateTimeJsonReaderWriter), nameof(Instance));
+ }
+
+ public sealed class LegacyDateTimeArrayReaderWriter : JsonValueReaderWriter
+ {
+ private static readonly JsonCollectionOfStructsReaderWriter Reader =
+ new(LegacyDateTimeJsonReaderWriter.Instance);
+
+ public override DateTime[] FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => (DateTime[])Reader.FromJsonTyped(ref manager, existingObject);
+
+ public override void ToJsonTyped(Utf8JsonWriter writer, DateTime[] value)
+ => Reader.ToJsonTyped(writer, value);
+
+ public override Expression ConstructorExpression
+ => Expression.New(typeof(LegacyDateTimeArrayReaderWriter));
+ }
+
+ [Theory, InlineData(false), InlineData(true)]
+ public async Task Nullable_converted_partition_uses_document_reader_null_policy(bool typeMappingDefault)
+ {
+ var factory = await InitializeNonSharedTest(
+ onModelCreating: b =>
+ {
+ var entity = b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ entity.HasKey(e => e.Id);
+ entity.HasPartitionKey(e => e.Partition);
+ var property = entity.Property(e => e.Partition)
+ .HasConversion(new ValueConverter(v => v, v => v));
+ if (!typeMappingDefault)
+ {
+ property.HasJsonValueReaderWriter();
+ }
+ },
+ configureConventions: c =>
+ {
+ if (typeMappingDefault)
+ {
+ c.DefaultTypeMapping().HasJsonValueReaderWriter();
+ }
+ },
+ seed: context =>
+ {
+ context.Add(new NullablePartitionKeyItem { Id = 1, Partition = null, Name = "initial" });
+ return context.SaveChangesAsync();
+ });
+ await using (var context = factory.CreateDbContext())
+ {
+ var item = await context.Set().SingleAsync(e => e.Partition == null);
+ Assert.Null(item.Partition);
+ Assert.Equal("initial", item.Name);
+ item.Name = "updated";
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ var item = await context.Set().SingleAsync(e => e.Partition == null);
+ Assert.Equal("updated", item.Name);
+ context.Remove(item);
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ Assert.False(await context.Set().AnyAsync(e => e.Partition == null));
+ }
+ }
+
+ private sealed class NullablePartitionKeyItem
+ {
+ public int Id { get; set; }
+ public string? Partition { get; set; }
+ public string Name { get; set; } = null!;
+ }
+
+ public sealed class NullPartitionReaderWriter : JsonValueReaderWriter
+ {
+ public static NullPartitionReaderWriter Instance { get; } = new();
+ public override bool HandlesNullWrites => true;
+ public override string FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => manager.CurrentReader.GetString()!;
+ public override void ToJsonTyped(Utf8JsonWriter writer, string value)
+ => writer.WriteStringValue(value ?? "sentinel");
+ public override Expression ConstructorExpression
+ => Expression.Property(null, typeof(NullPartitionReaderWriter), nameof(Instance));
+ }
+
+ [Theory, InlineData(false), InlineData(true)]
+ public async Task Custom_partition_reader_writer_is_used_for_save_read_query_update_and_delete(bool typeMappingDefault)
+ {
+ var factory = await InitializeNonSharedTest(
+ onModelCreating: b =>
+ {
+ b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ b.Entity().HasPartitionKey(e => e.Partition);
+ if (!typeMappingDefault)
+ {
+ b.Entity().Property(e => e.Partition)
+ .HasJsonValueReaderWriter();
+ }
+ },
+ configureConventions: c =>
+ {
+ if (typeMappingDefault)
+ {
+ c.DefaultTypeMapping().HasJsonValueReaderWriter();
+ }
+ },
+ seed: context =>
+ {
+ context.AddRange(
+ new FormattedPartitionKeyItem { Id = 1, Partition = 42, Name = "initial" },
+ new FormattedPartitionKeyItem { Id = 1, Partition = 43, Name = "other" });
+ return context.SaveChangesAsync();
+ });
+ var partition = 42;
+ await using (var context = factory.CreateDbContext())
+ {
+ var count = 1;
+ var page = await context.Set().Where(e => e.Id == count)
+ .OrderBy(e => e.Partition).Skip(count).Take(count).ToListAsync();
+ Assert.Equal(43, Assert.Single(page).Partition);
+ page = await context.Set().Where(e => e.Id == count)
+ .OrderBy(e => e.Partition).Skip(count - 1).Take(count).ToListAsync();
+ Assert.Equal(42, Assert.Single(page).Partition);
+
+ var item = await context.Set().SingleAsync(e => e.Id == 1 && e.Partition == partition);
+ Assert.Equal("initial", item.Name);
+ item.Name = "updated";
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ var item = await context.Set().WithPartitionKey(partition)
+ .SingleAsync(e => e.Name == "updated");
+ Assert.Equal(42, item.Partition);
+ context.Remove(item);
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ Assert.False(await context.Set().WithPartitionKey(partition).AnyAsync());
+ Assert.Equal("other", (await context.Set().WithPartitionKey(43).SingleAsync()).Name);
+ }
+ }
+
+ private sealed class FormattedPartitionKeyItem
+ {
+ public int Id { get; set; }
+ public int Partition { get; set; }
+ public string Name { get; set; } = null!;
+ public List Numbers { get; set; } = [];
+ }
+
+ [Fact]
+ public async Task Pagination_and_array_indexes_use_native_numbers_with_JSON_reader_writer_defaults()
+ {
+ var factory = await InitializeNonSharedTest(
+ onConfiguring: options => options.EnableSensitiveDataLogging(),
+ onModelCreating: b =>
+ {
+ b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ b.Entity().HasPartitionKey(e => e.Partition);
+ },
+ configureConventions: c => c.DefaultTypeMapping().HasJsonValueReaderWriter(),
+ seed: context =>
+ {
+ context.AddRange(
+ new FormattedPartitionKeyItem { Id = 1, Partition = 42, Name = "first", Numbers = [10, 20, 30] },
+ new FormattedPartitionKeyItem { Id = 1, Partition = 43, Name = "second", Numbers = [40, 50, 60] });
+ return context.SaveChangesAsync();
+ });
+
+ await using var context = factory.CreateDbContext();
+ var count = 1;
+ var query = context.Set().Where(e => e.Id == count).OrderBy(e => e.Partition);
+
+ var page = await query.Skip(count).Take(count)
+ .Select(e => e.Numbers.Skip((e.Id == count ? count : 0) + count - count).Take(count).ToArray()).ToArrayAsync();
+ Assert.Equal([50], Assert.Single(page));
+
+ page = await query.Skip(count - 1).Take(count)
+ .Select(e => e.Numbers.Take(count + 1).Skip(count).ToArray()).ToArrayAsync();
+ Assert.Equal([20], Assert.Single(page));
+
+ Assert.Equal(
+ 42,
+ (await query.Where(e => e.Numbers.ElementAt(count) == 20).FirstAsync()).Partition);
+
+ AssertSql(
+ """
+@count='1'
+@count0='1'
+@p='1'
+
+SELECT VALUE ARRAY_SLICE(c["Numbers"], ((((c["Id"] = @count) ? @count0 : 0) + @count0) - @count0), @count0)
+FROM root c
+WHERE (c["Id"] = @count)
+ORDER BY c["Partition"]
+OFFSET @p LIMIT @p
+""",
+ //
+ """
+@p3='2'
+@count='1'
+@count0='1'
+@p='0'
+@p2='1'
+
+SELECT VALUE ARRAY_SLICE(ARRAY_SLICE(c["Numbers"], 0, @p3), @count)
+FROM root c
+WHERE (c["Id"] = @count0)
+ORDER BY c["Partition"]
+OFFSET @p LIMIT @p2
+""",
+ //
+ """
+@count='1'
+@count0='1'
+
+SELECT VALUE c
+FROM root c
+WHERE ((c["Id"] = @count) AND (c["Numbers"][@count0] = "20"))
+ORDER BY c["Partition"]
+OFFSET 0 LIMIT 1
+""");
+ }
+
+ [Fact]
+ public async Task Count_and_LongCount_use_native_numbers_with_JSON_reader_writer_defaults()
+ {
+ var factory = await InitializeNonSharedTest(
+ onConfiguring: options => options.EnableSensitiveDataLogging(),
+ onModelCreating: b =>
+ {
+ b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ b.Entity().HasPartitionKey(e => e.Partition);
+ },
+ configureConventions: c => c.DefaultTypeMapping().HasJsonValueReaderWriter(),
+ seed: context =>
+ {
+ context.AddRange(
+ new FormattedPartitionKeyItem { Id = 1, Partition = 42, Name = "first" },
+ new FormattedPartitionKeyItem { Id = 2, Partition = 43, Name = "second" });
+ return context.SaveChangesAsync();
+ });
+
+ await using var context = factory.CreateDbContext();
+ var query = context.Set();
+ var id = 1;
+
+ Assert.Equal(2, await query.CountAsync());
+ Assert.Equal(1, await query.CountAsync(e => e.Id == id));
+ Assert.Equal(0, await query.CountAsync(e => e.Id == 0));
+ Assert.Equal(2L, await query.LongCountAsync());
+ Assert.Equal(1L, await query.LongCountAsync(e => e.Id == id));
+ Assert.Equal(0L, await query.LongCountAsync(e => e.Id == 0));
+
+ AssertSql(
+ """
+SELECT VALUE COUNT(1)
+FROM root c
+""",
+ //
+ """
+@id='1'
+
+SELECT VALUE COUNT(1)
+FROM root c
+WHERE (c["Id"] = @id)
+""",
+ //
+ """
+SELECT VALUE COUNT(1)
+FROM root c
+WHERE (c["Id"] = "0")
+""",
+ //
+ """
+SELECT VALUE COUNT(1)
+FROM root c
+""",
+ //
+ """
+@id='1'
+
+SELECT VALUE COUNT(1)
+FROM root c
+WHERE (c["Id"] = @id)
+""",
+ //
+ """
+SELECT VALUE COUNT(1)
+FROM root c
+WHERE (c["Id"] = "0")
+""");
+ }
+
+ [Fact]
+ public async Task Computed_boolean_projections_use_native_JSON_with_reader_writer_defaults()
+ {
+ var factory = await InitializeNonSharedTest(
+ onModelCreating: b =>
+ {
+ b.Entity().ToContainer("Entities").HasNoDiscriminator();
+ b.Entity().Property(e => e.Enabled)
+ .HasConversion(new Storage.ValueConversion.BoolToStringConverter("no", "yes"));
+ },
+ configureConventions: c => c.DefaultTypeMapping().HasJsonValueReaderWriter(),
+ seed: context =>
+ {
+ context.AddRange(
+ new FormattedBooleanItem { Id = 1, Enabled = true, Numbers = [1, 2] },
+ new FormattedBooleanItem { Id = 2, Enabled = false, Numbers = [] });
+ return context.SaveChangesAsync();
+ });
+ await using var context = factory.CreateDbContext();
+ var values = await context.Set().OrderBy(e => e.Id)
+ .Select(e => new
+ {
+ e.Enabled,
+ Comparison = e.Id > 1,
+ IsContained = new[] { 1, 3 }.Contains(e.Id),
+ HasElements = e.Numbers.Any(n => n > 1),
+ StartsWith = e.Name.StartsWith("a")
+ }).ToArrayAsync();
+ Assert.Collection(
+ values,
+ v =>
+ {
+ Assert.True(v.Enabled);
+ Assert.False(v.Comparison);
+ Assert.True(v.IsContained);
+ Assert.True(v.HasElements);
+ Assert.True(v.StartsWith);
+ },
+ v =>
+ {
+ Assert.False(v.Enabled);
+ Assert.True(v.Comparison);
+ Assert.False(v.IsContained);
+ Assert.False(v.HasElements);
+ Assert.True(v.StartsWith);
+ });
+ AssertSql(
+ """
+SELECT c["Enabled"], (c["Id"] > 1) AS Comparison, c["Id"] IN (1, 3) AS IsContained, EXISTS (
+ SELECT 1
+ FROM n IN c["Numbers"]
+ WHERE (n > 1)) AS HasElements, STARTSWITH(c["Name"], "a") AS StartsWith
+FROM root c
+ORDER BY c["Id"]
+""");
+ }
+
+ private sealed class FormattedBooleanItem
+ {
+ public int Id { get; set; }
+ public bool Enabled { get; set; }
+ public string Name { get; set; } = "abc";
+ public List Numbers { get; set; } = [];
+ }
+
+ [Theory,
+ InlineData(false, false, false), InlineData(false, true, false), InlineData(true, false, false), InlineData(true, true, false),
+ InlineData(false, false, true), InlineData(false, true, true), InlineData(true, false, true), InlineData(true, true, true)]
+ public async Task Custom_string_reader_writer_preserves_resource_IDs(bool typeMappingDefault, bool shadowId, bool convertedKey)
+ {
+ var factory = await InitializeNonSharedTest(
+ onModelCreating: b =>
+ {
+ var entity = b.Entity();
+ entity.ToContainer("Entities").HasNoDiscriminator();
+ entity.HasPartitionKey(e => e.Partition);
+ if (convertedKey)
+ {
+ entity.Property(e => e.Id).HasConversion(v => "converted:" + v, v => v.Substring("converted:".Length));
+ }
+
+ if (shadowId)
+ {
+ entity.HasShadowId();
+ }
+
+ if (!typeMappingDefault)
+ {
+ if (shadowId)
+ {
+ entity.Property("__id").HasJsonValueReaderWriter();
+ }
+ else
+ {
+ entity.Property(e => e.Id).HasJsonValueReaderWriter();
+ }
+ }
+ },
+ configureConventions: c =>
+ {
+ if (typeMappingDefault)
+ {
+ c.DefaultTypeMapping().HasJsonValueReaderWriter();
+ }
+ },
+ seed: context =>
+ {
+ context.Add(new FormattedIdItem { Id = "42", Partition = "tenant", Name = "initial" });
+ return context.SaveChangesAsync();
+ });
+
+ await using (var context = factory.CreateDbContext())
+ {
+ var item = await context.Set().SingleAsync(e => e.Id == "42" && e.Partition == "tenant");
+ Assert.Equal("initial", item.Name);
+ Assert.Contains("ReadItem", TestSqlLoggerFactory.SqlStatements.Last());
+ item.Name = "updated";
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ var item = await context.Set().SingleAsync(e => e.Id == "42" && e.Partition == "tenant");
+ Assert.Equal("updated", item.Name);
+ context.Remove(item);
+ await context.SaveChangesAsync();
+ }
+
+ await using (var context = factory.CreateDbContext())
+ {
+ Assert.False(await context.Set().AnyAsync());
+ }
+ }
+
+ private sealed class FormattedIdItem
+ {
+ public string Id { get; set; } = null!;
+ public string Partition { get; set; } = null!;
+ public string Name { get; set; } = null!;
+ }
+
+ public sealed class PrefixedStringReaderWriter : JsonValueReaderWriter
+ {
+ public override string FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => manager.CurrentReader.GetString()!["prefix:".Length..];
+
+ public override void ToJsonTyped(Utf8JsonWriter writer, string value)
+ => writer.WriteStringValue("prefix:" + value);
+
+ public override Expression ConstructorExpression
+ => Expression.New(typeof(PrefixedStringReaderWriter));
+ }
+
+ public sealed class Int32AsStringReaderWriter : JsonValueReaderWriter
+ {
+ public override int FromJsonTyped(ref Utf8JsonReaderManager manager, object? existingObject = null)
+ => int.Parse(manager.CurrentReader.GetString()!, CultureInfo.InvariantCulture);
+
+ public override void ToJsonTyped(Utf8JsonWriter writer, int value)
+ => writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
+
+ public override Expression ConstructorExpression
+ => Expression.New(typeof(Int32AsStringReaderWriter));
+ }
+
+ #endregion 31316
+
#region 35094
// TODO: Move these tests to a better location. They require nullable properties with nulls in the database.
diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs
index 58e575d3c49..9db10b8de30 100644
--- a/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/Query/PrimitiveCollectionsQueryCosmosTest.cs
@@ -816,52 +816,134 @@ WHERE ARRAY_CONTAINS(@nullableInts, c["NullableInt"])
public override async Task Parameter_collection_of_structs_Contains_struct()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(base.Parameter_collection_of_structs_Contains_struct);
+ await base.Parameter_collection_of_structs_Contains_struct();
- AssertSql();
+ AssertSql(
+ """
+@values='[22,33]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["WrappedId"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["WrappedId"]))
+""");
}
public override async Task Parameter_collection_of_structs_Contains_nullable_struct()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(base.Parameter_collection_of_structs_Contains_nullable_struct);
+ await base.Parameter_collection_of_structs_Contains_nullable_struct();
- AssertSql();
+ AssertSql(
+ """
+@values='[22,33]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["NullableWrappedId"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["NullableWrappedId"]))
+""");
}
public override async Task Parameter_collection_of_structs_Contains_nullable_struct_with_nullable_comparer()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(
- base.Parameter_collection_of_structs_Contains_nullable_struct_with_nullable_comparer);
+ await base.Parameter_collection_of_structs_Contains_nullable_struct_with_nullable_comparer();
- AssertSql();
+ AssertSql(
+ """
+@values='[22,33]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["NullableWrappedIdWithNullableComparer"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["NullableWrappedId"]))
+""");
}
public override async Task Parameter_collection_of_nullable_structs_Contains_struct()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(base.Parameter_collection_of_nullable_structs_Contains_struct);
+ await base.Parameter_collection_of_nullable_structs_Contains_struct();
- AssertSql();
+ AssertSql(
+ """
+@values='[null,22]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["WrappedId"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["WrappedId"]))
+""");
}
public override async Task Parameter_collection_of_nullable_structs_Contains_nullable_struct()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(base.Parameter_collection_of_nullable_structs_Contains_nullable_struct);
+ await base.Parameter_collection_of_nullable_structs_Contains_nullable_struct();
- AssertSql();
+ AssertSql(
+ """
+@values='[null,22]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["NullableWrappedId"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["NullableWrappedId"]))
+""");
}
public override async Task Parameter_collection_of_nullable_structs_Contains_nullable_struct_with_nullable_comparer()
{
- // Requires collections of converted elements
- await Assert.ThrowsAsync(
- base.Parameter_collection_of_nullable_structs_Contains_nullable_struct_with_nullable_comparer);
+ await base.Parameter_collection_of_nullable_structs_Contains_nullable_struct_with_nullable_comparer();
- AssertSql();
+ AssertSql(
+ """
+@values='[null,22]'
+
+SELECT VALUE c
+FROM root c
+WHERE ARRAY_CONTAINS(@values, c["NullableWrappedIdWithNullableComparer"])
+""",
+ //
+ """
+@values='[11,44]'
+
+SELECT VALUE c
+FROM root c
+WHERE NOT(ARRAY_CONTAINS(@values, c["NullableWrappedIdWithNullableComparer"]))
+""");
}
public override async Task Parameter_collection_of_strings_Contains_string()
diff --git a/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/Basic_cosmos_model/DataEntityType.cs b/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/Basic_cosmos_model/DataEntityType.cs
index d3a9b579678..c89cdcf4069 100644
--- a/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/Basic_cosmos_model/DataEntityType.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/Basic_cosmos_model/DataEntityType.cs
@@ -143,7 +143,8 @@ public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType bas
jsonValueReaderWriter: new JsonConvertedValueReaderWriter, IEnumerable>(
new JsonCollectionOfStructsReaderWriter(
JsonByteReaderWriter.Instance),
- new ValueConverter, byte[]>(byte[] (ReadOnlyMemory v) => ReadOnlyMemoryConverter.ToArray(v), ReadOnlyMemory (byte[] v) => ReadOnlyMemoryConverter.ToMemory(v))));
+ new ValueConverter, byte[]>(byte[] (ReadOnlyMemory v) => ReadOnlyMemoryConverter.ToArray(v), ReadOnlyMemory (byte[] v) => ReadOnlyMemoryConverter.ToMemory(v))),
+ elementMapping: CosmosTypeMapping.Default);
bytes.SetSentinelFromProviderValue(new byte[0]);
var list = runtimeEntityType.AddProperty(
diff --git a/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/ManyTypesEntityType.cs b/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/ManyTypesEntityType.cs
index 45e188731ff..7c25e601b74 100644
--- a/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/ManyTypesEntityType.cs
+++ b/test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/ManyTypesEntityType.cs
@@ -9,7 +9,6 @@
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal;
-using Microsoft.EntityFrameworkCore.Cosmos.ValueGeneration.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
@@ -35,7 +34,7 @@ public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType bas
baseEntityType,
discriminatorProperty: "Discriminator",
discriminatorValue: "ManyTypes",
- propertyCount: 169,
+ propertyCount: 168,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
@@ -43,8 +42,7 @@ public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType bas
typeof(CompiledModelTestBase.ManyTypesId),
propertyInfo: typeof(CompiledModelTestBase.ManyTypes).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CompiledModelTestBase.ManyTypes).GetField("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
- afterSaveBehavior: PropertySaveBehavior.Throw,
- valueConverter: new CompiledModelTestBase.ManyTypesIdConverter());
+ afterSaveBehavior: PropertySaveBehavior.Throw);
id.SetGetter(
CompiledModelTestBase.ManyTypesId (CompiledModelTestBase.ManyTypes instance) => ManyTypesUnsafeAccessors.Id(instance),
bool (CompiledModelTestBase.ManyTypes instance) => ManyTypesUnsafeAccessors.Id(instance).Equals(default(CompiledModelTestBase.ManyTypesId)));
@@ -71,15 +69,16 @@ public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType bas
shadowIndex: -1,
relationshipIndex: 0,
storeGenerationIndex: -1);
- id.TypeMapping = CosmosTypeMapping.Default.Clone(
+ id.TypeMapping = CosmosTypeMapping.Default.Clone(
comparer: ValueComparer.Default,
- providerValueComparer: DefaultValueComparer.Default,
- converter: new ValueConverter(int (CompiledModelTestBase.ManyTypesId v) => v.Id, CompiledModelTestBase.ManyTypesId (int v) => new CompiledModelTestBase.ManyTypesId(v)),
- jsonValueReaderWriter: new JsonConvertedValueReaderWriter(
- JsonInt32ReaderWriter.Instance,
- new ValueConverter(int (CompiledModelTestBase.ManyTypesId v) => v.Id, CompiledModelTestBase.ManyTypesId (int v) => new CompiledModelTestBase.ManyTypesId(v))));
- id.SetCurrentValueComparer(new CurrentProviderValueComparer(id));
- id.SetSentinelFromProviderValue(0);
+ providerValueComparer: DefaultValueComparer.Default,
+ converter: new ValueConverter(string (CompiledModelTestBase.ManyTypesId v) => v.Id.ToString(CultureInfo.InvariantCulture), CompiledModelTestBase.ManyTypesId (string v) => new CompiledModelTestBase.ManyTypesId(int.Parse(v, CultureInfo.InvariantCulture))),
+ jsonValueReaderWriter: new JsonConvertedValueReaderWriter(
+ JsonStringReaderWriter.Instance,
+ new ValueConverter(string (CompiledModelTestBase.ManyTypesId v) => v.Id.ToString(CultureInfo.InvariantCulture), CompiledModelTestBase.ManyTypesId (string v) => new CompiledModelTestBase.ManyTypesId(int.Parse(v, CultureInfo.InvariantCulture)))));
+ id.SetCurrentValueComparer(new CurrentProviderValueComparer(id));
+ id.SetSentinelFromProviderValue("0");
+ id.AddAnnotation("Cosmos:PropertyName", "id");
var @bool = runtimeEntityType.AddProperty(
"Bool",
@@ -6676,25 +6675,6 @@ public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType bas
JsonStringReaderWriter.Instance,
new ValueConverter(string (Uri v) => ((object)v).ToString(), Uri (string v) => new Uri(v, UriKind.RelativeOrAbsolute))));
- var __id = runtimeEntityType.AddProperty(
- "__id",
- typeof(string),
- afterSaveBehavior: PropertySaveBehavior.Throw,
- valueGeneratorFactory: new IdValueGeneratorFactory().Create);
- __id.SetAccessors(
- string (IInternalEntry entry) => entry.ReadShadowValue(1),
- string (IInternalEntry entry) => entry.ReadShadowValue(1),
- string (IInternalEntry entry) => entry.ReadOriginalValue(__id, 168),
- string (IInternalEntry entry) => entry.GetCurrentValue(__id));
- __id.SetPropertyIndexes(
- index: 168,
- originalValueIndex: 168,
- shadowIndex: 1,
- relationshipIndex: -1,
- storeGenerationIndex: -1);
- __id.TypeMapping = CosmosTypeMapping.Default;
- __id.AddAnnotation("Cosmos:PropertyName", "id");
-
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
@@ -6872,7 +6852,6 @@ public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
var uInt8ReadOnlyCollection = runtimeEntityType.FindProperty("UInt8ReadOnlyCollection");
var uri = runtimeEntityType.FindProperty("Uri");
var uriToStringConverterProperty = runtimeEntityType.FindProperty("UriToStringConverterProperty");
- var __id = runtimeEntityType.FindProperty("__id");
var key = runtimeEntityType.FindKey(new[] { id });
key.SetPrincipalKeyValueFactory(KeyValueFactoryFactory.CreateSimpleNonNullableFactory(key));
key.SetIdentityMapFactory(IdentityMapFactoryFactory.CreateFactory(key));
@@ -6890,16 +6869,16 @@ public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
var structuralType3 = ((CompiledModelTestBase.ManyTypes)(source.Entity));
var liftedArg3 = ((ISnapshot)(new Snapshot, string, string, string, string, string, string, string, string, string, string, string, string, string>((source.GetCurrentValue(nullableTimeSpan) == null ? null : ((ValueComparer)(((IProperty)nullableTimeSpan).GetValueComparer())).Snapshot(source.GetCurrentValue(nullableTimeSpan))), (source.GetCurrentValue(nullableUInt16) == null ? null : ((ValueComparer)(((IProperty)nullableUInt16).GetValueComparer())).Snapshot(source.GetCurrentValue(nullableUInt16))), (((IEnumerable