使用 C# 和 cosmos 客户端从 cosmos db 中删除文档

Jai*_*Jai 2 c# delete-row azure-cosmosdb azure-cosmosdb-sqlapi

我是 Cosmos DB 的新手,在阅读了 microsoft 文档后,我试图从 Cosmos db 中删除记录。我试图尽可能地遵循这个例子。正在找到并读取记录,但在尝试删除时遇到了未找到的错误。

集合已分区,我在示例中提到了分区键,但仍然导致错误。

    private async Task QueryItemsAsync()
    {
        var sqlQueryText = "SELECT * FROM c WHERE c.tenantId = '5c6cb2d77c1c2edc001b9007' and c.id = 'abae8abf-5836-464f-8129-1f0e83a1f639'";

        QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
        FeedIterator<Order> queryResultSetIterator = this.container.GetItemQueryIterator<Order>(queryDefinition);

        List<Order> orders = new List<Order>();

        while (queryResultSetIterator.HasMoreResults)
        {
            FeedResponse<Order> currentResultSet = await queryResultSetIterator.ReadNextAsync();
            foreach (Order o in currentResultSet)
            {
                orders.Add(o);
                Console.WriteLine("\tRead {0}\n", o);       
            }
        }
    }         
    private async Task DeleteFamilyItemAsync()
    {
        var partitionKeyValue = "tenantId";
        var orderId = "abae8abf-5836-464f-8129-1f0e83a1f639";

        // Delete an item. Note we must provide the partition key value and id of the item to delete
        ItemResponse<Order> orderResponse = await this.container.DeleteItemAsync<Order>(orderId, new PartitionKey(partitionKeyValue));
        Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, orderId);
    }
Run Code Online (Sandbox Code Playgroud)

如下所示,正在读取记录,因此正在找到它,但是当我尝试删除它时,它并没有被删除。读取 {"Id":null,"patientId":null,"orchestrationId":null,"preOrderId":"88557ec1-dccb-4397-9ce4-20b6aeb1d636","cartId":"adc463ef-7f38-4fa8-8f37-e510 ","confirmationNum":"QDQ-9244014-14708","cartConfirmationNum":"IBM-8622967-14079","countryCode":null,"type":"order","cancelDate":null,"id": “abae8abf-5836-464f-8129-1f0e83a1f639”}

NotFound 错误发生:CosmosRequestException;StatusCode=NotFound;SubStatusCode=0;ActivityId=6dd52d23-68c8-4e6d-b4ff-70cd2a6921cf;RequestCharge=1.24;Message=响应状态码不表示成功:404 子状态:0 原因:()。演示结束,按任意键退出。

Nic*_*sas 6

问题出在你的partitionKeyValue. 您提供的是分区键定义而不是值。该值是实际租户 ID 而不是 text tenantId

您的删除代码应如下所示:

private async Task DeleteFamilyItemAsync()
{
    var partitionKeyValue = "5c6cb2d77c1c2edc001b9007"; // <-- This is the change
    var orderId = "abae8abf-5836-464f-8129-1f0e83a1f639";

    // Delete an item. Note we must provide the partition key value and id of the item to delete
    ItemResponse<Order> orderResponse = await this.container.DeleteItemAsync<Order>(orderId, new PartitionKey(partitionKeyValue));
    Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, orderId);
}
Run Code Online (Sandbox Code Playgroud)