首页 > 其他分享 >EF Core – JSON Column

EF Core – JSON Column

时间:2022-11-06 10:56:49浏览次数:77  
标签:Core Column EF Entity JSON Address public

前言

SQL Server 支持 JSON, 以前写过一篇介绍 SQL Server – Work with JSON. 但 EF Core 一直没有支持.

直到 EF Core 7.0 才支持.

 

参考

Docs – JSON Columns

 

配置

复制代码
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public Address Address { get; set; } = null!;
}

public class Address
{
    public string Line1 { get; set; } = "";
    public string Line2 { get; set; } = "";
}
复制代码

Address 是一个对象. 过往我们会把它配置成 Owned Entity, 属性 Line1, Line2 分别占据数据库 2 个 column. column name 是 Address_Line1, Address_Line2

这样是 ok 的, 但有时候我们希望它在数据库就一个 column, 然后用 JSON 格式保存资料. 反正数据库也支持 JSON 查询 (只是性能不容易优化), 一堆 column 毕竟很乱.

声明使用 JSON Column

它算是 Owned Entity 的扩展, 表面上依然是 Owned Entity, 但多了一个 ToJson() 声明

复制代码
modelBuilder.Entity<Customer>().ToTable("Customer");
modelBuilder.Entity<Customer>().Property(e => e.Name).HasMaxLength(256);
modelBuilder.Entity<Customer>().OwnsOne(e => e.Address, addressBuilder =>
{
    addressBuilder.ToJson();
    addressBuilder.Property(e => e.Line1).HasMaxLength(256);
    addressBuilder.Property(e => e.Line2).HasMaxLength(256);
});
复制代码

数据库长相

生成出来的数据长这样. Address 值就是 JSON 格式

查询的 LINQ 是完全一样的, EF Core 在背地里会转换成对应的 JSON Query

var customers = await db.Customers.Where(e => e.Address.Line1 == "lorem 1").ToListAsync();

Query

 

嵌套

如果有多层, 只需要在最上层设置 ToJson() 就可以了.

 

Update Value

像平常一样直接 update Entity 就可以了. EF Core 会转换成 JSON_MODIFY 语句去更新

 

 

OwnsMany

JSON for array 我还没有处理过, 以后补上 TODO...

 

Limitation

Github – Support spatial types in JSON columns

Github – Json: add support for collection of primitive types

Github – Support LINQ to JSONPATH querying

 

标签:Core,Column,EF,Entity,JSON,Address,public
From: https://www.cnblogs.com/wl-blog/p/16862152.html

相关文章