In this post, let’s explore a great new enhancement available in EF Core 10.0. EF Core 10.0 now supports partially updating JSON columns with ExecuteUpdate/ExecuteUpdateAsync.
Let's consider the following DbContext.
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public required Contact Contact { get; set; }
}
public class Contact
{
public required Address Address { get; set; }
}
public class Address
{
public required string Street { get; set; }
public required string City { get; set; }
public required string State { get; set; }
public required string PostalCode { get; set; }
} public class MyDbContext : DbContext{
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer("<ConnectionString>", x =>
{
x.UseCompatibilityLevel(170); // Microsoft SQL Server 2025
});
}
override protected void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Customer>(x =>
{
x.ComplexProperty(x => x.Contact, x => x.ToJson());
});
}
}
With above code Customer.Contact column will get created as a json data type (EF Core 10.0: Support for JSON Data Type in Microsoft SQL Server)
Now let's say we need to do a partial update on Customer.Contact.PostalCode.
await context.Customers
.Where(x => x.Name == "John Doe")
.ExecuteUpdateAsync(setters =>
setters
.SetProperty(c => c.Contact.Address.PostalCode, "98102")
);
Above will create the following SQL query.
UPDATE [c]
SET [Contact].modify('$.Address.PostalCode', @p)
FROM [Customers] AS [c]
WHERE [c].[Name] = N'John Doe'
Note the partial update on PostalCode using the modify method. The modify method is currently in preview and only available in Microsoft SQL Server 2025 Preview.
This even works with older versions of Microsoft SQL Server, where the JSON data is stored as nvarchar(max) column.
For example,
optionsBuilder
.UseSqlServer("<ConnectionString>", x =>
{
x.UseCompatibilityLevel(160); // Microsoft SQL Server 2022
});
This would create the Customer.Contact column as nvarchar(max) and above ExecuteUpdateAsync would still work. In this case, generated query would be something like following.
UPDATE [c]
SET [c].[Contact] = JSON_MODIFY([c].[Contact], '$.Address.PostalCode', @p)
FROM [Customers] AS [c]
WHERE [c].[Name] = N'John Doe'
Note: this only works when mapping JSON data with ComplexProperty and not with owned entities.
More read:
   What's New in EF Core 10
   JSON Data Type
Hope this helps.
Happy Coding.
 
 
No comments:
Post a Comment