2017-04-25 59 views
5

我正在构建.Net控制台应用程序以读取DocumentDB中的信息。控制台应用程序具有来自EventHub的数据,并在进入云时插入/更新最近的数据。Azure DocumentDB读取文档资源未找到

我想从DocumentDB读取单数文档,并且我可以在请求文档之前确认文档存在。

if (DocumentDBRepository<DocumentDBItem>.DoesItemExist(name)) 
{ 
    device = await DocumentDBRepository<DocumentDBItem>.GetItemAsync(name); 
} 

我用this教程从微软关于建立一个存储库访问DocumentDB纪录,并成功地在使用几乎所有的方法。我可以更新/删除/查询数据库,但我无法读取单个项目。

首先它抛出请求PartitionKey的异常。所以我修改了这个方法来将DB使用的PartitionKey添加到请求中。当我加入它抛出一个消息的另一个异常PartitionKey,“资源未找到”

public static async Task<T> GetItemAsync(string id) 
{ 
    try 
    { 
     RequestOptions options = new RequestOptions(); 
     options.PartitionKey = new PartitionKey("DeviceId"); 
     Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), options); 
     return (T)(dynamic)document; 
    } 
    catch (DocumentClientException e) 
    { 
     if (e.StatusCode == HttpStatusCode.NotFound) 
     { 
      return null; 
     } 
     else 
     { 
      throw; 
     } 
    } 
} 

PartitionKeyFromAzure

我已经修改了我的电话使用“GetItemsAsyc”,并得到文件的IEnumerable并获得列表中的第一项,但它没有意义,为什么我可以使用教程中的所有其他方法,但是这个方法继续抛出异常,说“找不到资源”。

异常我越来越:

"Message: {\"Errors\":[\"Resource Not Found\"]}\r\nActivityId: e317ae66-6500-476c-b70e-c986c4cbf1d9, Request URI: /apps/e842e452-2347-4a8e-8588-2f5f8b4803ad/services/2c490552-a24d-4a9d-a786-992c07356545/partitions/0281cfdd-0c60-499f-be4a-289723a7dbf9/replicas/131336364114731886s" 
+0

这绝对是您正在寻找的文档的正确分区键,我认为您需要指定它的值(我在代码中看不到)?我使用的代码与您的代码非常相似,除非没有分区键(因为我使用的是不支持它的较低优惠吞吐量),并且它工作正常。 –

+0

这是我用于数据库的唯一分区键,并且传递给该方法的ID是Key作为PartitionKey。在这种情况下'DeviceId'。 –

+0

在我的情况下,我将分区键保存为一个整数,但是我将它作为一个字符串进行搜索,因此无法工作。一旦我修好它的工作正常 – joalcego

回答

6

the documentation所示,您需要提供分区键的,存储分区键的字段不是名称。因此,您需要将设备ID作为参数添加到您的方法中,并将其值传递给构造函数PartitionKey

从例如:

// Read document. Needs the partition key and the ID to be specified 
Document result = await client.ReadDocumentAsync(
    UriFactory.CreateDocumentUri("db", "coll", "XMS-001-FE24C"), 
    new RequestOptions { PartitionKey = new PartitionKey("XMS-0001") }); 

因此,对于你的代码:

public static async Task<T> GetItemAsync(string id, string deviceId) 
{ 
    try 
    { 
     RequestOptions options = new RequestOptions(); 
     options.PartitionKey = new PartitionKey(deviceId); 
     Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), options); 
     return (T)(dynamic)document; 
    } 
    catch (DocumentClientException e) 
    { 
     if (e.StatusCode == HttpStatusCode.NotFound) 
     { 
      return null; 
     } 
     else 
     { 
      throw; 
     } 
    } 
} 
+1

这是我的问题。在我的情况下,Id和DeviceId是相同的。感谢您的帮助。昨天,我正在撞墙,试图完成这个任务。 –

0

今天我确切的问题。

在读取在文档DB文件,
当格式的文档链接(DBS/DBID ../colls/COLLID .. /文档/文档ID ..)

解决方案:
文档客户端抛出“资源未找到”2种情况:
1.收集ID错误
2. partitionKey给出了一些问题。也就是说,要么给了不正确的partitionKey,要么partitionKey不是必需的,而是给出了一个。