ExecuteUpdate writes a column/JSON value into a value-converted JSON property without applying the converter, corrupting the document
维护者通常 2 天内回复
还没有人认领这个 Issue。
评估
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 新手友好度
- 48/100
调研方向
Start by reading RelationalQueryableMethodTranslatingExpressionVisitor.TrySerializeScalarToJson, named in the issue, and trace how ExecuteUpdate translates setters for JSON properties. Compare the source value mapping with the target property's converter, then inspect existing tests for JSON ExecuteUpdate behavior and add coverage for column-to-JSON setters. Done means the converter is applied or the existing unsupported-operation error is raised, with regression tests covering the reported cases.
由索引模型根据 Issue 内容生成。
描述
Bug description
When ExecuteUpdate sets a property inside a JSON complex type from a regular column (or from another JSON property), and the target JSON property has a value converter that the source doesn't share, EF writes the source's raw relational value into the JSON document. The target property's converter is never applied.
- Enum stored as int in a column → JSON enum property with
HasConversion<string>():1is written instead of"Shipped", and every later query that materializes the entity throws. - Int column → JSON int property with a scaling converter: the unconverted value is written and silently read back wrong (5 kg is stored as
5instead of5000, read back as0). - Same with another JSON property:
SetProperty(o => o.Details.Status, o => o.Details.LegacyStatus)copies the number.
Constants, parameters and SaveChanges all apply the converter correctly. For non-number/string/bool provider types (e.g. DateTime, Guid) the same column-to-JSON setter correctly throws "'ExecuteUpdate' cannot currently set a property in a JSON column to a regular, non-JSON column" (#36688), so it looks like the number/string/bool shortcut in RelationalQueryableMethodTranslatingExpressionVisitor.TrySerializeScalarToJson checks the provider type of the value's type mapping and never compares it with the target property's mapping/converter.
Your code
using Microsoft.EntityFrameworkCore;
var useSqlServer = args.Contains("sqlserver");
using (var ctx = new ShopContext(useSqlServer))
{
ctx.Database.EnsureDeleted();
ctx.Database.EnsureCreated();
ctx.Orders.Add(new Order { Id = 1, Status = OrderStatus.Shipped, WeightKg = 5, Details = new() { Status = OrderStatus.Pending, WeightKg = 1 } });
ctx.SaveChanges();
}
using (var ctx = new ShopContext(useSqlServer))
{
// Copy regular columns into JSON properties that have value converters
ctx.Orders.ExecuteUpdate(s => s
.SetProperty(o => o.Details.WeightKg, o => o.WeightKg)
.SetProperty(o => o.Details.Status, o => o.Status));
Console.WriteLine("Stored JSON: " + ctx.Database.SqlQueryRaw<string>("SELECT Details AS Value FROM Orders").Single());
}
using (var ctx = new ShopContext(useSqlServer))
{
try
{
var order = ctx.Orders.AsNoTracking().Single();
Console.WriteLine($"Details.Status = {order.Details.Status}, Details.WeightKg = {order.Details.WeightKg}");
}
catch (Exception e)
{
Console.WriteLine($"{e.GetType()}: {e.Message}");
}
}
public enum OrderStatus { Pending, Shipped }
public class Order
{
public int Id { get; set; }
public OrderStatus Status { get; set; } // regular column, int (default mapping)
public int WeightKg { get; set; } // regular column, kilograms
public OrderDetails Details { get; set; } = new();
}
public class OrderDetails
{
public OrderStatus Status { get; set; } // stored as a string in JSON
public int WeightKg { get; set; } // stored as grams in JSON
}
public class ShopContext(bool useSqlServer) : DbContext
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (useSqlServer)
optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=EfJsonConverterRepro;Trusted_Connection=True;TrustServerCertificate=True");
else
optionsBuilder.UseSqlite("Data Source=repro.db");
optionsBuilder.LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], Microsoft.Extensions.Logging.LogLevel.Information);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Order>(b =>
{
b.Property(o => o.Id).ValueGeneratedNever();
b.ComplexProperty(o => o.Details, d =>
{
d.ToJson();
d.Property(x => x.Status).HasConversion<string>();
d.Property(x => x.WeightKg).HasConversion(kg => kg * 1000, g => g / 1000);
});
});
}
SQLite:
UPDATE "Orders" AS "o"
SET "Details" = json_set(json_set("o"."Details", '$.WeightKg', "o"."WeightKg"), '$.Status', "o"."Status")
Stored JSON: {"Status":1,"WeightKg":5}
System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
SQL Server:
UPDATE [o]
SET [o].[Details] = JSON_MODIFY(JSON_MODIFY([o].[Details], '$.WeightKg', [o].[WeightKg]), '$.Status', [o].[Status])
FROM [Orders] AS [o]
Stored JSON: {"Status":1,"WeightKg":5}
System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
Expected: either {"Status":"Shipped","WeightKg":5000}, or the existing "cannot set a property in a JSON column to a regular, non-JSON column" translation error. Without the Status setter there is no exception at all: Details.WeightKg silently reads back as 0 instead of 5.
Stack traces
System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType)
at System.Text.Json.Utf8JsonReader.GetString()
at Microsoft.EntityFrameworkCore.Storage.Json.JsonStringReaderWriter.FromJsonTyped(Utf8JsonReaderManager& manager, Object existingObject)
at Microsoft.EntityFrameworkCore.Storage.Json.JsonConvertedValueReaderWriter`2.FromJsonTyped(Utf8JsonReaderManager& manager, Object existingObject)
at lambda_method83(Closure, QueryContext, Object[], JsonReaderData)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.IncludeJsonEntityReference[TStructural,TRelatedStructural](...)
at lambda_method82(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
Verbose output
Not applicable; SQL shown above.
EF Core version
11.0.0 (also reproduced on daily 12.0.0-alpha.1.26577.105)
Database provider
Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.SqlServer
Target framework
.NET 11.0
Operating system
Windows 10
IDE
dotnet CLI
I'd like to work on this and will wait for a maintainer to confirm before opening a PR.
- 主要语言
- C#
- 星标
- 14.8k
- 派生
- 3.5k
- 平均合并
- 2 天 22 小时
- 30 天内合并 PR
- 158
环境准备
在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
dotnet/efcore 的其他 Issue
-
Test bug: Include_collection_with_cross_apply_with_filter relies on nondeterministic ORDER BY with Take可能已有人在做 @Mohamedadel-prog 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 66/100
维护者通常 2 天内回复
-
customer-reported
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 2 天内回复
-
Compiled model: generate a deterministic model ID可能已有人在做 @rgroenewoudt 今天认领。 未关闭
难度 4/5 3-5 天 新手友好度 35/100
维护者通常 2 天内回复
-
customer-reported
难度 4/5 3-5 天 新手友好度 48/100
维护者通常 2 天内回复
-
难度 4/5 3-5 天 新手友好度 35/100
维护者通常 2 天内回复
相似的 Issue
-
area-VM-meta-mono untriaged
难度 2/5 1-3 小时 新手友好度 75/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 79/100
BattletechModders/ModTek#256 · 1 条评论 ·
-
难度 2/5 1-3 小时 新手友好度 82/100
microsoft/sqltoolsservice#2851 ·
维护者通常 1 天内回复
-
enhancement
难度 2/5 1-3 小时 新手友好度 68/100
维护者通常 1 天内回复
-
triage/untriaged
难度 2/5 1-3 小时 新手友好度 82/100
unoplatform/uno#26844 ·
维护者通常 1 天内回复