使用null数组项更新Json时出错

时间:2011-11-18 21:51:22

标签: c# json patch ravendb

我正在通过代码修改Json文档。 Json有数组嵌套项。我的代码失败了,因为我认为它无法处理特定数组为空的Json文档。如何检查null或空数组,并使此代码仅适用于具有数据的数组。

store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:patrons" },
new[]
{
  new PatchRequest
      {
          Type = PatchCommandType.Modify,
          Name = "Privilege",
          Nested = new[]
           {
             new PatchRequest {Type = PatchCommandType.Set, Name="Level",  

             Value="Gold"}, 
           }
       }
}, allowStale: false);

Json文档看起来像:

    {
             "Privilege": [{
                           "Level": "Gold",
                           "Code": "12312",
                           "EndDate": "12/12/2012"
                          }],
             "Phones":    [{
                           "Cell": "123123",
                           "Home": "9783041284",
                           "Office": "1234123412"
                          }]
             "MiddleInitial":"F"

           }

有些Json文档看起来像(在这种情况下,注意Privilege是一个空数组)

 {
         "Privilege": [],
         "Phones":    [{
                       "Cell": "123123",
                       "Home": "9783041284",
                       "Office": "1234123412"
                      }]
         "MiddleInitial":"F"

       }

2 个答案:

答案 0 :(得分:2)

修补命令期望数据存在,因此您需要使用索引来查找没有空Privileges列表的文档。

首先你需要一个像这样的索引:

public override IndexDefinition CreateIndexDefinition()
{
    return new IndexDefinitionBuilder<Patron>
    {
        Map = docs => from doc in docs
                      where doc.Privileges != null
                      select new { HasPrivileges = doc.Privileges.Count == 0 ? false : true }
    }.ToIndexDefinition(Conventions);
}

然后,您只将修补程序应用于HasPrivileges = true的文档,如下所示:

store.DatabaseCommands.UpdateByIndex("PatronByPrivilege",
              //Only apply the patch to Patrons that have a privilege
              new IndexQuery { Query = "HasPrivileges:true" },
                     new[]
                     {
                          new PatchRequest
                          {
                               .........

我创建了一个full code sample,任何问题都告诉我。

答案 1 :(得分:1)

看起来您正在尝试在数组上设置属性,但数组没有属性,它们只能包含其他对象。