c# - 如何在 C# 中执行 json 查询?

标签 c# json sql-server asp.net-core

我正在使用支持 Json 的 SQL Server 2017。但是我正在使用无法查询 json 的 EF 核心。

那我怎么查询呢?

例子

  SELECT
      *, JSON_VALUE (Attributes, '$.year') AS Year
  FROM 
      items
  WHERE 
      JSON_VALUE(Attributes, '$.year') = '2017'

我如何在 C#/ASP.NET Core 中查询它? ADO.NET?

最佳答案

我假设您的 items 是如下模型:

    public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Attributes { get; set; }
}

如果是这样并且您不需要 Year,您可以像下面这样尝试 FromSql:

string sQuery = "SELECT *, JSON_VALUE (Attributes, '$.year') AS Year FROM  Customer WHERE JSON_VALUE(Attributes, '$.year') = '2018'";               

var customerEF = await _context.Customer.FromSql(sQuery).ToListAsync();

对于这种方式,您只能返回在 Customer 模型中定义的列。

如果你想返回 CustomerYear 列,我建议你尝试 Dapper喜欢:

using (var connection = new SqlConnection(_configuration.GetConnectionString("DefaultConnection")))
        {                
            string sQuery = "SELECT *, JSON_VALUE (Attributes, '$.year') AS Year FROM  Customer WHERE JSON_VALUE(Attributes, '$.year') = '2018'";
            var customerDapper = connection.QueryFirstOrDefault<CustomerVM>(sQuery);                           
        }

使用 Dapper,使用 Year 列定义新模型:

    public class CustomerVM: Customer
{
    public string Year { get; set; }
}

更新

避免 SQL 注入(inject)。

尝试传递 SQL 参数。

string sQuery = "SELECT *, JSON_VALUE (Attributes, '$.year') AS Year FROM  Customer WHERE JSON_VALUE(Attributes, '$.year') = @Year";
var year = new SqlParameter("Year", "2018");
var customerEF = await _context.Customer.FromSql(sQuery, year).ToListAsync();

关于c# - 如何在 C# 中执行 json 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598456/

相关文章:

c++ - 我不希望 JSON 在 C++ 中转义撇号。如何解决这个问题?

sql - 比较同表sql中的下一条记录

java - Spring Boot Gradle Java应用程序中的SQL Server依赖项

sql-server - 确定表的行大小

c# - 将 JSON.NET JObject 的属性/标记转换为字典键

c# - 多个foreach用于多个列表数据

c# - 读取 Dependency walker 输出

php - Swift - JSON 响应以\u201c 开头并以\u201d 结尾

c# - 在 C# 中通过 TCP 进行面向对象的通信

php - 安卓/PHP : how to POST/GET JSON data from Android to php