Support defaults for missing JSON members in ComplexProperty().ToJson() for schema evolution
Maintainers usually reply within 2 days
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 38/100
Research direction
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.
Written by the indexing model from the issue text.
Description
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
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.5k
- Avg merge
- 3d 7h
- Merged PRs (30d)
- 182
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/efcore
-
customer-reported
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 2 days
-
GroupBy element `OrderBy(...).First()`/`MaxBy` over an owned type mapped to its own table fails to translatePossibly taken @cincuranet claimed this today. Openarea-groupby area-query
Difficulty 4/5 3-5 days Newbie friendliness 25/100
dotnet/efcore#39833 · 1 assignee ·
Maintainers usually reply within 2 days
-
SQLite: Polygon.Length translates to GLength, which returns 0Possibly taken @cincuranet claimed this today. Openarea-query area-sqlite
Difficulty 3/5 1-2 days Newbie friendliness 45/100
dotnet/efcore#39826 · 1 assignee ·
Maintainers usually reply within 2 days
-
Migration lock with LockReleaseBehavior.Transaction doesn't prevent concurrent migrations since per-migration transactionsPossibly taken @AndriySvyryd claimed this 1 day ago. Openarea-migrations
dotnet/efcore#39824 · 1 assignee ·
Maintainers usually reply within 2 days
-
Querying a TPC base type with a JSON complex property throwsPossibly taken @cincuranet claimed this 1 day ago. Openarea-query
Difficulty 4/5 3-5 days Newbie friendliness 22/100
dotnet/efcore#39814 · 1 assignee ·
Maintainers usually reply within 2 days
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
SubtitleEdit/subtitleedit#17247 ·
Maintainers usually reply within 1 day
-
Restore test cleanup fails on Windows when restored files are read-onlyPossibly taken @JamBalaya56562 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
duplicati/duplicati#8046 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
Maintainers usually reply within 1 day
-
Bundles Documentation
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
pyrevitlabs/pyRevit#4285 ·
Maintainers usually reply within 1 day