在C#中的cosmos db文档中存储和访问字典列表

时间:2019-02-02 10:17:49

标签: c# azure-cosmosdb-sqlapi

我正尝试以以下格式将文档存储在cosmosDb中

          {
             "id":"1",
             "Devices": [
              {
                "deviceid":"1",
                "LastUpdateTime":utc.now
              },
              {
                "deviceid":"1",
                "LastUpdateTime":utc.now
              }
       ]
       "LastUpdateTime":utc.now
   }

以下是我的课程的模式

          public class datasave
           {
           public string id { get; set; }
            public IDictionary<string, DateTime> Devices { get; set; }
            public DateTime LastUpdated { get; set; }
          }

如果没有ID为ID的文档,我正在尝试创建文档,否则获取文档以更新特定deviceId的Lastupdatedtime

以下是我提取和更新的逻辑

                      var exisitingdocument = await GetExistingDocument(new List<string> { "id" }).ConfigureAwait(false);
                    if (exisitingdocument != null && exisitingdocument.Count > 0)
                    {
                        try
                        {
                            var updateDocument = exisitingdocument.SingleOrDefault();
                            updateDocument.Devices[DeviceId] = DateTime.UtcNow;
                            updateDocument.LastUpdated = DateTime.UtcNow;
                            await UpdateDocumentincosmos(updateDocument).ConfigureAwait(false);
                        }
                        catch(Exception ex)
                        {
                            logger.LogInformation($"{ex}")
                            throw;
                        }
    else
                    {
                        try
                        {
                            var createnewdocument = new datasave();
                            createnewdocument.Id = Id;
                            createnewdocument.Devices.Add(DeviceId, DateTime.UtcNow);
                            createnewdocument.LastUpdated = DateTime.UtcNow;
                            await UpdateDocumentinCosmos(createnewdocument).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            throw ;
                        }

这使我抛出异常对象引用未设置为实例的情况

0 个答案:

没有答案