EFCore使用JSON_VALUE查询json对象的值
-
Intro
SqlServer 从2016开始支持 JSON 操作,可以使用 JSON_VALUE 查询 JSON 对象的某个属性值,更多介绍,现在公司的一些项目主要是使用 EF Core,手写sql较少,针对比较简单的 JSON_VALUE 查询想通过 DbFunction 来实现,于是就有了这篇文章的探索。
定义
JSON_VALUE
DbFunctionpublic static class DbFunctions { [DbFunction("JSON_VALUE", "")] public static string JsonValue(string column, [NotParameterized] string path) { throw new NotSupportedException(); } }
在 DbContext 中注册 DbFunction
重写 DbContext 的
OnModelCreating
方法,在OnModelCreating
方法中注册 DbFunctionpublic class TestDbContext : DbContext { public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } public DbSet<TestEntity> TestEntities { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDbFunction(() => DbFunctions.JsonValue(default(string), default(string))); } } public class TestEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Extra { get; set; } public DateTime CreatedAt { get; set; } }
使用注册的 DbFunction 查询 JSON_VALUE
数据库中添加了三条测试数据,测试数据如下:
var loggerFactory = new LoggerFactory(); loggerFactory.AddLog4Net(); var optionsBuilder = new DbContextOptionsBuilder<TestDbContext>() .UseLoggerFactory(loggerFactory) .UseSqlServer("server=.;database=Test;Integrated Security=True"); var db = new TestDbContext(optionsBuilder.Options); var names = db.TestEntities.AsNoTracking().Select(t => DbFunctions.JsonValue(t.Extra, "$.Name")).ToArray();
监控生成的Sql语句
我这里通过 log4net 记录执行的 sql 语句,监控到执行的sql语句如下:
SELECT JSON_VALUE([t].[Extra], N'$.Name') FROM [TestEntities] AS [t]
Source
Reference
- https://docs.microsoft.com/en-us/sql/t-sql/functions/json-value-transact-sql?view=sql-server-2017
- https://docs.microsoft.com/en-us/sql/relational-databases/json/json-path-expressions-sql-server?view=sql-server-2017
- https://stackoverflow.com/questions/52017204/expression-tree-to-sql-with-ef-core
- https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#database-scalar-function-mapping
转 https://www.jianshu.com/p/34b77a0fba6d
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)