簡體   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