dotnet / dotnet/efcore

SaveChanges over complex JSON types with partial updates

Open
#36,429 1 comment 4 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-complex-types area-json area-save-changes
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

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;

```c#
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 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().ComplexProperty(b => b.Related, rrb => rrb.ToJson());

// With owned mapping, we get partial update with JSON_MODIFY()
// modelBuilder.Entity().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; }
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.