分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

EFCore使用JSON_VALUE查询json对象的值

发布时间:2023-09-06 02:30责任编辑:熊小新关键词:jsjson

EFCore使用JSON_VALUE查询json对象的值

Intro

SqlServer 从2016开始支持 JSON 操作,可以使用 JSON_VALUE 查询 JSON 对象的某个属性值,更多介绍,现在公司的一些项目主要是使用 EF Core,手写sql较少,针对比较简单的 JSON_VALUE 查询想通过 DbFunction 来实现,于是就有了这篇文章的探索。

定义 JSON_VALUE DbFunction

 ???public static class DbFunctions ???{ ???????[DbFunction("JSON_VALUE", "")] ???????public static string JsonValue(string column, [NotParameterized] string path) ???????{ ???????????throw new NotSupportedException(); ???????} ???}

在 DbContext 中注册 DbFunction

 ???public 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

示例代码: https://github.com/WeihanLi/WeihanLi.EntityFramework/blob/master/samples/WeihanLi.EntityFramework.Samples/Program.cs

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

EFCore使用JSON_VALUE查询json对象的值

原文地址:https://www.cnblogs.com/weihanli/p/use-json-value-in-ef-core.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved