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

Aperta
#39,846 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
csharp, sql, sqlite
Ambito
backend, database

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
C#
Stelle
14.8k
Fork
3.5k
Merge medio
2g 22h
PR unite (30g)
158

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/efcore

Tutte le issue di dotnet/efcore

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.