ExecuteUpdate writes a column/JSON value into a value-converted JSON property without applying the converter, corrupting the document

未关闭
#39,846 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 2 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
csharp, sql, sqlite
领域
backend, database

调研方向

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>(): 1 is 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 5 instead of 5000, read back as 0).
  • 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

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

dotnet/efcore 的其他 Issue

查看 dotnet/efcore 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。