【问题标题】:Is there any c# code for deleting cosmos DB documents是否有任何用于删除 cosmos DB 文档的 c# 代码
【发布时间】:2019-07-11 13:02:29
【问题描述】:

我正在进行 .net api 开发,其中一项任务是根据条件删除一些文档。这些文档驻留在 Cosmos DB 中。

我已经尝试通过存储过程,但没有得到删除记录的正确 SP。我尝试使用带有 where 条件的 select 查询获取文档,并通过循环获取并传递文档 ID,我尝试删除 using DeleteDocumentAsync

//---Deleting Document based on documentId from corresponding DbName,CollectionName-----------//

 private async Task DeleteSecurityDocument(string databaseName, string collectionName, string documentName)
        {

                string endPoint = ConfigurationManager.AppSettings["DocDbEndPoint"];
                string masterKey = ConfigurationManager.AppSettings["DocDbmasterKey"];

                var client = new DocumentClient(new Uri(endPoint), masterKey);

                await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentName));    

        }

【问题讨论】:

  • 我以前从未使用过 Cosmos。但是一些简单的谷歌搜索显示DeleteDocumentAsync 返回一个响应对象,而您忽略了它。您是否尝试检查它以查看它可能会告诉您什么信息?
  • 您的收藏是否已分区?另外,您使用的是哪个 Cosmos DB API?

标签: c# azure azure-cosmosdb sql-delete


【解决方案1】:

此代码适用于我:

var options = new RequestOptions { PartitionKey = new PartitionKey(PartitionKeyValue) };
var docUri = UriFactory.CreateDocumentUri(databaseId, collectionId, documentId);
var doc = await _client.ReadDocumentAsync(docUri, options);

if (doc != null)
{
    return await _client.DeleteDocumentAsync(doc.SelfLink, options);
}

其中optionsRequestOptions 的一个实例,如果您使用分区集合,则应该设置 PartitionKey

这里删除前大概阅读文档是不需要的,直接放docUri就可以了,这个我没查过(代码在项目中存在很久了)。

【讨论】:

  • 感谢您的帮助。 var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, documentName); Microsoft.Azure.Documents.Client.RequestOptions 选项 = null;等待客户端.DeleteDocumentAsync(docUri,选项);我用过这个但没有工作..var doc = await _client.ReadDocumentAsync(docUri, options);我试过这条线,但得到 null 并且 Selflink 没有启用。我对这个 cosmos DB 不熟悉..有人可以帮我吗?
  • 如果ReadDocumentAsync返回null,表示没有找到这个标识符的文档。确保在这一行var docUri = UriFactory.CreateDocumentUri(databaseId, collectionId, documentId) 中传递正确的值:数据库名称、集合名称和文档的“id”属性的值。另一件重要的事情 - 如果您的集合是分区的,请确保您在请求选项中传递正确的 PartitionKey 值。例如。如果集合上的分区键称为“tenantId”,则需要将 document.tenantId 的值传递给 PartitionKey 属性。
【解决方案2】:
/---------------.delete documents ------------/
var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, documentName);
RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey(Partitionkeyvalue) };
var deleteresponse = await client.DeleteDocumentAsync(docUri, options);

现在它对我来说很好。问题是关于partitiokeyvalue。谢谢

【讨论】:

  • 这应该是对另一个问题的评论,您应该接受该答案
  • 注意我还在那个答案中添加了相关的代码行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2023-03-22
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多