繁体   English   中英

如何在 CosmosDB 中向 SqlParameter 提供 JSON 片段作为值

[英]How can I provide an JSON fragment as an value to SqlParameter in CosmosDB

在 Cosmos DB 中,我可以使用 Json 片段作为查询的 where 子句的一部分,这样

SELECT * FROM c WHERE c.path.to.propery={"where":{"value":{"is":true}}}

产生结果(当然如果有的话)

现在我想在使用SqlParamter查询时使用相同的想法

var stmt = new SqlQuerySpec
{
  QueryText = "SELECT * FROM c WHERE c.path.to.propery=@myjson",
  Parameters = new SqlParameterCollection()
  {
     new SqlParameter{ Name = "@myjson", Value = ??? } 
  }
};

知道什么(如果有的话)需要去而不是??? 在查询中有 json 片段{"where":{"value":{"is":true}}}

编辑

简单地添加一个string作为参数值是行不通的,因为字符串会正确地包含在"以防止 SQL 注入攻击。

使用匿名对象,如

myjson = new { where = new { value = new { @is = true } } }

可能会起作用(我还没有尝试过)但在我的特定情况下不起作用,因为 JSON 及其结构在编译时是未知的。

我找到了 cosmos DBs StringToObject函数形式的解决方案,以便

var myjson =  @"{""where"":{""value"":{""is"":true}}}"
var stmt = new SqlQuerySpec
{
    QueryText = "SELECT * FROM c WHERE c.path.to.propery=StringToObject(@myjson)",
    Parameters = new SqlParameterCollection()
    {
        new SqlParameter{ Name = "@myjson", Value = myjson } 
    }
};

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM