gpt4 book ai didi

c# - Azure DocumentDB 读取文档资源未找到

转载 作者:可可西里 更新时间:2023-11-01 08:22:23 25 4
gpt4 key购买 nike

我正在构建一个 .Net 控制台应用程序来读取 DocumentDB 中的信息。控制台应用程序具有来自 EventHub 的数据,并在最新数据进入云时插入/更新数据。

我正在尝试从 DocumentDB 读取单个文档,并且我可以在请求文档之前确认该文档存在。

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

我用了this来自 Microsoft 的有关构建用于访问 DocumentDB 记录的存储库的教程,并且成功地使用了几乎所有方法。我可以更新/删除/查询数据库,但无法读取单个项目。

首先,它抛出请求 PartitionKey 的异常。因此我修改了方法,将数据库正在使用的 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"

最佳答案

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;
}
}
}

关于c# - Azure DocumentDB 读取文档资源未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com