【问题标题】:Azure Document DB UpdateDocAzure 文档数据库更新文档
【发布时间】:2016-10-14 16:15:46
【问题描述】:

我从 azure document db 开始。我试图更新现有文档。当我使用以下查询时,一切正常:

dynamic Team2Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.Id == "t002").AsEnumerable().FirstOrDefault();
Team2Doc.TeamName = "UPDATED_TEAM_2";
await client.ReplaceDocumentAsync(Team2Doc);

但是如果使用下面的代码:

dynamic Team2Doc = client.CreateDocumentQuery<Document>(documentCollection.DocumentsLink).Where(d => d.TeamName== "team1").AsEnumerable().FirstOrDefault();
Team2Doc.TeamName = "UPDATED_TEAM_2";
await client.ReplaceDocumentAsync(Team2Doc);

我收到此错误:

"最佳重载方法匹配 'Microsoft.Azure.Documents.Client.DocumentClient.ReplaceDocumentAsync(Microsoft.Azure.Documents.Document, Microsoft.Azure.Documents.Client.RequestOptions)' 有一些无效 论据”

是否可以通过其中一个属性检索文档并更新文档?

【问题讨论】:

    标签: c# azure azure-cosmosdb


    【解决方案1】:

    where 子句试图查询 TeamName 属性,该属性在 Document 类中不存在。

    将可查询的类型更改为您的数据模型应该可以解决它。

    例如,假设您有以下数据模型:

    public class EmployeeDocument : Document
    {   
         // Other properties that you may have similarly defined ....
    
         public class string TeamName 
         {
            get
            {
                return this.GetValue<string>("TeamName");
            }
    
            set
            {
                this.SetValue("TeamName", value);
            }
         }
    }
    

    然后你可以像这样修改你的查询:

    var team2Doc = client.CreateDocumentQuery<EmployeeDocument>(documentCollection.DocumentsLink).Where(d => d.TeamName== "team1").AsEnumerable().FirstOrDefault();
    team2Doc.TeamName = "UPDATED_TEAM_2";
    await client.ReplaceDocumentAsync(team2Doc);
    

    请注意,在创建可查询的文档时,您必须使用 EmployeeDocument,而不是 Document 类。这将让您查询 EmployeeDocument 属性。

    SQL 版本

    如果您拥有大量数据模型,则为每个现有数据模型创建文档模型可能不可行。在这种情况下,您可能需要尝试 SQL 查询语法。

    Refer to Aravind's answer in this post。他使用的示例是删除文档,但也可以轻松修改以更新它们。

    【讨论】:

      【解决方案2】:

      您也可以使用 Id 创建模型:

      public class Employee
      {            
           [JsonPropery("id")]
           public class string Id { get; set; }
      
           public class string TeamName { get; set; }
      }
      

      然后使用它的 Id 替换文档:

      var employee= client
          .CreateDocumentQuery<Employee>(documentCollection.DocumentsLink)
          .Where(d => d.TeamName== "team1")
          .AsEnumerable()
          .FirstOrDefault();
      
      employee.TeamName = "team2";
      
      var documentUri = UriFactory.CreateDocumentUri(databaseName, collectionName, employee.Id);
      
      await client.ReplaceDocumentAsync(employee);
      

      【讨论】:

      • 嗯。我认为这行不通。 Employee 不是 Document 类型,所以你怎么能调用 ReplaceDocumentAsync() 作为它的文档。此外,简单地调用employee.TeamName = "team2"; 不会使文档无效,因此它不会更新。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2018-03-16
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多