SQL Server: a TimeSpan of a day or more in a JSON column is read back wrong, with no error, when a query reads the property

Abierto
#39,456 0 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 2 días

@AndriySvyryd ya está trabajando en esto.

Desde el 30/10/2026.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
57/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
csharp, sql

Línea de trabajo

Start by tracing the SQL Server translation of JSON-backed TimeSpan property access; the report shows the generated expression CAST(JSON_VALUE([h].[Doc], '$.Length') AS time). Check the provider tests for JSON projections and comparisons of TimeSpan, then add coverage for values of a day or more. Done means querying JSON-backed values gives the expected result or fails clearly, rather than returning a truncated time.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

area-json area-query
Bug description

A TimeSpan property inside a JSON column (OwnsOne(...).ToJson() or ComplexProperty(...).ToJson()) holding a day or more is stored correctly and reads back correctly when the entity is materialized. But a query that reads the property translates it to CAST(JSON_VALUE(...) AS time), and that returns a different value, with no error.

EF writes 26 hours into the JSON as "1:2:00:00". Converting that text to time gives 01:02:00, so the following are all wrong:

  • a projection of the property returns 01:02:00;
  • a filter compares 01:02:00, so the row counts as "shorter than 2 hours".

SQL Server's time holds less than a day, so EF can write a value into JSON that it can't query back. Outside JSON the same value fails loudly: SaveChanges into a time column throws, and a parameter throws OverflowException. Here nothing does, and the answer depends on whether the property is materialized or queried.

I'd expect the query to answer 1.02:00:00, or to fail on translation or execution, rather than return a different time of day.

This is related to #39222, fixed by #39364 for 12.0, which makes an out-of-range TimeSpan literal throw. That fix doesn't reach this case: the value comes from the JSON document, not from a literal, so the CAST(... AS time) still runs and still answers without an error.

Your code
using Microsoft.EntityFrameworkCore;

await using (var setup = new Db())
{
    await setup.Database.EnsureDeletedAsync();
    await setup.Database.EnsureCreatedAsync();
    setup.Add(new Holder { Doc = new() { Length = TimeSpan.FromHours(26) } });
    await setup.SaveChangesAsync();
}

await using var db = new Db();
Console.WriteLine((await db.Holders.SingleAsync()).Doc.Length);                     // 1.02:00:00
Console.WriteLine(await db.Holders.Select(h => h.Doc.Length).SingleAsync());       // 01:02:00
Console.WriteLine(await db.Holders.CountAsync(h => h.Doc.Length < TimeSpan.FromHours(2)));  // 1
Console.WriteLine(db.Holders.Select(h => h.Doc.Length).ToQueryString());
// SELECT CAST(JSON_VALUE([h].[Doc], '$.Length') AS time) FROM [Holders] AS [h]

public sealed class Holder
{
    public int Id { get; set; }
    public Doc Doc { get; set; } = new();
}

public sealed class Doc
{
    public TimeSpan Length { get; set; }
}

public sealed class Db : DbContext
{
    public DbSet<Holder> Holders => Set<Holder>();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
        options.UseSqlServer("Server=localhost,1433;Database=TimeSpanJson;User Id=sa;Password=...;TrustServerCertificate=True");

    protected override void OnModelCreating(ModelBuilder model) =>
        model.Entity<Holder>().OwnsOne(h => h.Doc, doc => doc.ToJson());   // ComplexProperty(h => h.Doc, doc => doc.ToJson()) answers the same
}

The JSON column holds {"Length":"1:2:00:00"}.

Stack traces

None: no exception is thrown.

Verbose output

(not applicable)

EF Core version

10.0.14 (also seen on 10.0.12)

Database provider

Microsoft.EntityFrameworkCore.SqlServer 10.0.14, on Azure SQL Edge 15.0.2000.1574 (arm64). With 10.0.12, the same on SQL Server 2022 (Linux container).

Target framework

.NET 10.0

Operating system

macOS 27 (arm64), and Ubuntu (SQL Server 2022 run)

IDE

(none; dotnet CLI)

Lenguaje dominante
C#
Estrellas
14.8k
Forks
3.5k
Merge medio
2 d 22 h
PR fusionados (30 d)
158

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de dotnet/efcore

Todos los issues de dotnet/efcore

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.