我正在使用支持 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
模型中定义的列。
如果你想返回 Customer
和 Year
列,我建议你尝试 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/