简体   繁体   中英

Unable to delete specific document from cosmos db via sdk?

在此处输入图像描述 I am using DeleteDocumentAsync as per below code.

 public static void DeleteErrorLog(List<string> LogID, string collectionName)
        {
            FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true };
            try
            {
                //getting resource id for a document with given logid

                var db = client.CreateDatabaseQuery().Where(x => x.Id == databaseName).ToList().First();
                var coll = client.CreateDocumentCollectionQuery(db.SelfLink).Where(x => x.Id == collectionName).ToList().First();
                var docs = client.CreateDocumentQuery(coll.SelfLink, queryOptions).Where(x => x.Id == LogID[0]).AsEnumerable().Single();
                var collectionUri = UriFactory.CreateDocumentUri(databaseName, collectionName, docs.ResourceId);
                client.DeleteDocumentAsync(collectionUri);

            }
            catch (Exception) { throw; }
        }

Every value is populating correctly and I am getting the document that I need to delete still unable to delete it? Any help is greatly appreciated

You are probably missing the PartitionKey for the delete operation:

var documentUri = UriFactory.CreateDocumentUri(databaseName, collectionName, LogID[0]);
client.DeleteDocumentAsync(documentUri, new RequestOptions(){PartitionKey=new PartitionKey(LogID[0])}).GetAwaiter().GetResult();

Also, if you already know the Id, which in your case is LogID[0] , you don't need the Query.

You're not awaiting client.DeleteDocumentAsync , which means your catch will not catch exceptions that occur in the Task that's created - it will silently fail.

My guess is that due to this, there is an exception being thrown in DeleteDocumentAsync that's not subsequently caught where expected.

Ideally, this method would be re-written to use async / await , then your try catch will pick up any exceptions being thrown:

public static async Task DeleteErrorLog(List<string> LogID, string collectionName)
{
    ...
    await client.DeleteDocumentAsync(collectionUri);
    ...
}

You'll have to make sure that the code calling this method also uses await .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM