EF Core 7.0 – JSON Column
@@EF Core 7 json 列
前言
SQL Server 支持 JSON, 以前写过一篇介绍 SQL Server – Work with JSON. 但 EF Core 一直没有支持。直到 EF Core 7.0 才支持。
EF Core 7 包含对 JSON 列的提供程序无关的支持,以及 SQL Server 的实现。此支持允许将从 .NET 类型生成的聚合映射到 JSON 文档。可以在聚合上使用普通的 LINQ 查询,这些查询将转换为钻取到 JSON 所需的相应查询构造。EF7 还支持更新和保存对 JSON 文档所做的更改。具体参考 https://learn.microsoft.com/zh-cn/ef/core/what-is-new/ef-core-7.0/whatsnew#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 语句去更新
Array OwnsMany
除了对象, Array 也是可以的. 使用 OwnsMany. 操作和 OwnsOne 一摸一样.
但是 List<string> 就没有办法哦. 而且 Array 是不支持过滤的.
modelBuilder.Entity<Customer>().OwnsMany(e => e.Addresses, addressesBuilder => { addressesBuilder.ToJson(); addressesBuilder.Property(e => e.Line1).HasMaxLength(256); addressesBuilder.Property(e => e.Line2).HasMaxLength(256); });
query
var customer = await db.Customers.Where(e => e.Addresses.Count() > 3).ToListAsync();
上面这句会直接报错...目前还不支持
Limitation
Github – Support spatial types in JSON columns :https://github.com/dotnet/efcore/issues/28811
Github – Json: add support for collection of primitive types:https://github.com/dotnet/efcore/issues/28688
Github – Support LINQ to JSONPATH querying:https://github.com/dotnet/efcore/issues/28616
转 https://blog.csdn.net/sD7O95O/article/details/128586679
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2022-07-14 你知道5分钟法则和10字节法则么?
2022-07-14 SpringCloudAlibaba分布式事务解决方案Seata实战与源码分析-上
2022-07-14 NET Core 实现后台任务(定时任务)BackgroundService(二)
2022-07-14 系统总出故障怎么办,或许你该学学稳定性建设!
2021-07-14 如何快速实现一个虚拟 DOM 系统
2021-07-14 RabbitMQ 常用知识点总结
2021-07-14 你真的懂 export default 吗?