我正在使用带有Cosmos DB的ASP.NET Core构建一个restful API . 有一个需要分区键的GetItemById请求 .
public static async Task<T> GetItemAsync(string itemId, string name)
{
try
{
Document document =
await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, itemId),
new RequestOptions() { PartitionKey = new PartitionKey(name) });
return (T)(dynamic)document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
GetByIdAsync()函数调用此GetItemAsync()方法 .
[HttpGet("{itemId}")]
public async Task<IActionResult> GetByIdAsync(string itemId, string name)
{
var item = await DocumentDBRepository<TodoItem>.GetItemAsync(itemId, name);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
该URL将是http://localhost:54084/api/todo/f323307b-142f-46f3-9072-12f41cc74e87
我的Azure CosmosDB容器如下所示:
但是当我运行它时,它给了我一个错误
{Microsoft.Azure.Documents.DocumentClientException:提供的分区键或者与集合中的定义不对应,或者与文档中指定的分区键字段值不匹配 .
2 回答
在Cosmos DB中,主键是分区键和行键(“id”)的组合 . 两者的组合唯一地标识一行 - 而不仅仅是“id” . 因此,您需要在分区键中指定Name的值以查找该项(不为null) .
如果您的应用程序没有自然PK,那么您应该考虑将“/ id”设置为分区键(并传递id和分区键的值)
我想到了 . 我收到此错误的原因是因为我的集合中没有设置分区键 . 这就是我应该删除的原因
new RequestOptions() { PartitionKey = new PartitionKey(name) }
删除后,它正常工作 .