Support defaults for missing JSON members in ComplexProperty().ToJson() for schema evolution
Los mantenedores suelen responder en 2 días
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 38/100
Línea de trabajo
Start with the Repro.cs mapping and the ComplexProperty().ToJson() entry point, then reproduce the old-document case using the SQL Server provider. Done means an agreed, tested behavior distinguishes an absent JSON member from explicit null while addressing CLR defaults; the issue does not name a repository test or implementation file.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Bug description
Feature request
When a complex type is mapped to a JSON column via ComplexProperty().ToJson(), and the stored JSON is missing a property that was added in a later version of the CLR model, EF Core currently materializes that property as null.
This happens even when the property has a CLR default value assigned via a property initializer or constructor.
This makes JSON schema evolution difficult for document-like models stored in relational databases.
For example:
- Version A of the application stores a JSON document without property
NewProperty. - Version B of the application adds
NewPropertyto the CLR type and initializes it to a default value. - EF Core loads a row written by Version A.
- Since the JSON payload does not contain
NewProperty, EF Core materializes it asnull. - The default value from the CLR model is not preserved.
This is surprising because the application model expresses a valid default value, but that value is lost during EF materialization.
Desired behavior
It would be useful if EF Core provided a way to control how missing JSON members are handled when materializing complex types mapped with ComplexProperty().ToJson().
For example, one of the following behaviors would solve this scenario:
- Preserve CLR property initializers / constructor defaults when a JSON member is absent.
- Allow per-property configuration of a default value for absent JSON members.
- Allow a model-level or JSON-mapping-level option for missing-member handling.
- Allow a materialization hook specifically for JSON complex types before nullability validation / change tracking.
The important distinction is between:
- JSON member is present with value
null - JSON member is absent because the row was written by an older application version
For schema evolution, an absent member should ideally be treated differently from an explicit null.
Why this matters
This is common when using JSON columns as document storage with versioned application models.
A typical deployment scenario is:
- Version A stores documents with schema A.
- Version B adds a new non-nullable property with a default value.
- Existing rows are still physically stored as schema A.
- Loading those rows through the Version B model produces partially invalid domain objects.
This creates a read hazard: application code expects the property to have its default value, but it is unexpectedly null.
It may also create a save hazard depending on nullability configuration, required properties, nested complex types, or validation logic.
The current workaround is to manually normalize the object graph after materialization, for example through ChangeTracker.Tracked, an IMaterializationInterceptor, or application-level post-load logic. However, this is error-prone and must be repeated for every JSON document type.
Another workaround is to backfill all existing JSON rows whenever a property is added, but this is not always practical for large tables, multi-tenant systems, or distributed deployments.
Example
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Record> Records => Set<Record>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseNpgsql("Host=localhost;Database=efrepro;Username=postgres;Password=postgres");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Record>(entity =>
{
entity.ToTable("records");
entity.HasKey(x => x.Id);
entity.ComplexProperty(x => x.Document, document =>
{
document.ToJson("document");
});
});
}
}
public class Record
{
public Guid Id { get; set; }
public MyDocument Document { get; set; } = new();
}
public class MyDocument
{
// Existing property in schema version A.
public string Name { get; set; } = "";
// Added in schema version B.
// Existing JSON rows written by version A do not contain this property.
public string NewProperty { get; set; } = "default-value";
}
Assume an existing row contains JSON written by the previous application version:
{
"Name": "Document written by version A"
}
When the row is loaded by the newer application version, the expected materialized object would be:
record.Document.NewProperty == "default-value";
But the actual value is:
record.Document.NewProperty == null;
The CLR initializer is not preserved for the absent JSON member.
Current workaround
The workaround is to normalize the JSON document after materialization:
public class MyDocument
{
public string Name { get; set; } = "";
public string? NewProperty { get; set; } = "default-value";
public void Normalize()
{
NewProperty ??= "default-value";
}
}
For example:
using Microsoft.EntityFrameworkCore.Diagnostics;
public sealed class DocumentMaterializationInterceptor : IMaterializationInterceptor
{
public object InitializedInstance(
MaterializationInterceptionData materializationData,
object entity)
{
if (entity is Record record)
{
record.Document?.Normalize();
}
return entity;
}
}
However, this requires every application to implement its own schema-evolution/defaulting layer outside of EF Core.
Related issue
This looks related to:
- #38625
That issue focuses on absent nested complex collections materializing as null instead of empty collections.
This feature request is for the more general schema-evolution case where any newly-added JSON-mapped complex type property may be absent from older stored JSON documents, and EF Core does not preserve CLR defaults during materialization.
EF Core version
EF Core version: [please fill in, e.g. 10.0.x or 11.0 preview x]
Database provider
Provider: [please fill in, e.g. Npgsql.EntityFrameworkCore.PostgreSQL / Microsoft.EntityFrameworkCore.SqlServer]
Target framework
Target framework: [please fill in, e.g. .NET 10.0 / .NET 11.0]
Your code
<See Above>
Stack traces
Verbose output
EF Core version
10
Database provider
Microsoft.EntityFrameworkCore.SqlServer
Target framework
.NET 10
Operating system
No response
IDE
No response
- Lenguaje dominante
- C#
- Estrellas
- 14.8k
- Forks
- 3.5k
- Merge medio
- 3 d 7 h
- PR fusionados (30 d)
- 182
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de dotnet/efcore
-
customer-reported
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 2 días
-
GroupBy element `OrderBy(...).First()`/`MaxBy` over an owned type mapped to its own table fails to translatePosiblemente ocupada @cincuranet la tomó hoy. Abiertoarea-groupby area-query
Dificultad 4/5 3-5 días Aptitud para principiantes 25/100
dotnet/efcore#39833 · 1 asignado ·
Los mantenedores suelen responder en 2 días
-
SQLite: Polygon.Length translates to GLength, which returns 0Posiblemente ocupada @cincuranet la tomó hoy. Abiertoarea-query area-sqlite
Dificultad 3/5 1-2 días Aptitud para principiantes 45/100
dotnet/efcore#39826 · 1 asignado ·
Los mantenedores suelen responder en 2 días
-
Migration lock with LockReleaseBehavior.Transaction doesn't prevent concurrent migrations since per-migration transactionsPosiblemente ocupada @AndriySvyryd la tomó hace 1 día. Abiertoarea-migrations
dotnet/efcore#39824 · 1 asignado ·
Los mantenedores suelen responder en 2 días
-
Querying a TPC base type with a JSON complex property throwsPosiblemente ocupada @cincuranet la tomó hace 1 día. Abiertoarea-query
Dificultad 4/5 3-5 días Aptitud para principiantes 22/100
dotnet/efcore#39814 · 1 asignado ·
Los mantenedores suelen responder en 2 días
Todos los issues de dotnet/efcore
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
SubtitleEdit/subtitleedit#17247 ·
Los mantenedores suelen responder en 1 día
-
Restore test cleanup fails on Windows when restored files are read-onlyPosiblemente ocupada @JamBalaya56562 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
duplicati/duplicati#8046 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 1 día
-
Bundles Documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
pyrevitlabs/pyRevit#4285 ·
Los mantenedores suelen responder en 1 día