EF Core – JSON Column

前言

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

 

posted @   dreamw  阅读(240)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示