首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C#中进行json查询?

问如何在C#中进行json查询?
EN

Stack Overflow用户
提问于 2018-10-02 04:30:12
回答 1查看 238关注 0票数 2

我使用的是SQL Server 2017,它支持Json。然而,我使用的是EF内核,它不能查询json。

那我该怎么做查询呢?

示例

代码语言:javascript
复制
  SELECT
      *, JSON_VALUE (Attributes, '$.year') AS Year
  FROM 
      items
  WHERE 
      JSON_VALUE(Attributes, '$.year') = '2017'

如何在C# / ASP.NET核心中查询?ADO.NET?

EN

回答 1

Stack Overflow用户

发布于 2018-10-02 15:35:46

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

代码语言:javascript
复制
    public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Attributes { get; set; }
}

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

代码语言:javascript
复制
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模型中定义的列。

如果您想返回Customer和Year列中的列,我建议您尝试Dapper,如下所示:

代码语言:javascript
复制
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列定义新模型:

代码语言:javascript
复制
    public class CustomerVM: Customer
{
    public string Year { get; set; }
}

更新

避免SQL内联。

尝试传递SQL参数。

代码语言:javascript
复制
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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52598456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档