Skip to content

SaveChanges over complex JSON types with partial updates #36429

@roji

Description

@roji

When changing a single property in a complex JSON object, the entire JSON document gets saved to the database inside of doing a partial update on the property which changed;

await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Blogs.Add(new Blog
{
    Name = "Blog 1",
    Related = new Related
    {
        Foo = 1,
        Title = "Related 1"
    }
});

await context.SaveChangesAsync();

context.ChangeTracker.Clear();

var blog = await context.Blogs.SingleAsync();

blog.Related.Foo = 2;

await context.SaveChangesAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>().ComplexProperty(b => b.Related, rrb => rrb.ToJson());

        // With owned mapping, we get partial update with JSON_MODIFY()
        // modelBuilder.Entity<Blog>().OwnsOne(b => b.Related, x => x.ToJson());
    }
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Related Related { get; set; }
}

public class Related
{
    public int Foo { get; set; }
    public string Title { get; set; }
}

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions