简体   繁体   English

使用 Entity Framework Core 在 SQL Server 查询中参数化 OPENJSON

[英]Parameterized OPENJSON in SQL Server query using Entity Framework Core

context.Set<BlogKeyValuePair>()
   .FromSql("SELECT [key], value FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId=1), '$.@path')", 
        new SqlParameter("@path", "path.to.data"));

On first sighting this should work correctly and @path should be replace by path.to.data but it doesn't, an SqlException is thrown with the following error:第一次看到这应该可以正常工作, @path应该被@path替换,但事实并非如此,抛出path.to.data并出现以下错误:

System.Data.SqlClient.SqlException: Incorrect syntax near '@path'. System.Data.SqlClient.SqlException:'@path' 附近的语法不正确。

Seems like SQL server does not replace the parameter because it is a parameter inside the OPENJSON function.似乎 SQL 服务器没有替换参数,因为它是OPENJSON函数内部的参数。

Looking for secure workarounds.寻找安全的解决方法。

SQL does not recognize the variable because you put it inside a string: SQL 无法识别该变量,因为您将其放入字符串中:

-- Wrong:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.@path')

-- Correct:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)

Code:代码:

context
    .Set<BlogKeyValuePair>()
    .FromSql(@"
        SELECT [key], value
        FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)",
        new SqlParameter("@path", "path.to.data"));

This works for me in SSMS, so @marsze's answer should work.这在 SSMS 中对我有用,所以@marsze 的答案应该有效。

declare @path nvarchar(2000) = 'ArrayValue';

DECLARE @json NVARCHAR(4000) = N'{  
   "StringValue":"John",  
   "IntValue":45,  
   "TrueValue":true,  
   "FalseValue":false,  
   "NullValue":null,  
   "ArrayValue":["a","r","r","a","y"],  
   "ObjectValue":{"obj":"ect"}  
}'

SELECT *
FROM OPENJSON(@json, '$.' + @path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心; 在对(MS)SQL Server的查询中使用ORDER BY - Entity Framework Core; using ORDER BY in query against a (MS) SQL Server 来自 Entity Framework Core 中表达式树的参数化查询 - Parameterized Query from an Expression Tree in Entity Framework Core 将 Include 与参数化输入一起使用时,Entity Framework Core 抛出 - Entity Framework Core throws when using Include with parameterized input 在 sql server json 列中搜索并使用实体框架核心使用它 - Searching in sql server json column and consume it using entity framework core 为什么使用参数化查询或实体框架会阻止sql注入? - Why does using parameterized queries or entity framework prevent sql injection? 将 SQL 查询转换为 Entity Framework Core 2.1 - Translate SQL query into Entity Framework Core 2.1 SQL Server IN子句的实体框架核心 - Entity Framework Core to SQL Server IN Clause 实体框架核心-仅使用EF,执行SQL Server并获取结果的“查询处理器耗尽了内部资源”错误 - Entity Framework Core - “The query processor ran out of internal resources” error only using EF, executing SQL server and get the results 空间类型实体框架核心SQL Server - Spatial type Entity Framework Core SQL Server Entity Framework Core 使用 ifs 创建查询 - Entity Framework Core create query using ifs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM