sup*_*nja 1 api azure database-partitioning asp.net-core azure-cosmosdb
我正在使用 ASP.NET Core 和 Cosmos DB 构建一个宁静的 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
URL 将是http://localhost:54084/api/todo/f323307b-142f-46f3-9072-12f41cc74e87
但是当我运行这个时,它给了我一个错误
{Microsoft.Azure.Documents.DocumentClientException:提供的分区键与集合中的定义不对应或与文档中指定的分区键字段值不匹配。
在 Cosmos DB 中,主键是分区键和行键(“id”)的组合。两者的组合唯一地标识了一行——而不是单独的“id”。所以需要在partition key中指定Name的值来查找item(不为null)。
如果您的应用程序没有自然 PK,那么您应该考虑将“/id”设置为分区键(并同时传递 id 和分区键的值)
| 归档时间: |
|
| 查看次数: |
6806 次 |
| 最近记录: |