简体   繁体   中英

Trying to delete a row from Cosmos DB in C# code

I am trying to delete of a row from a Cosmos db container. I have only ID. The PartitionKey is different ie, Category column. But I don't have category value while deleting. I am new to Cosmos DB. Is there any approach to perform this?

 var task = await this.MainContainer.DeleteItemAsync<T>(id, new PartitionKey("Category1"));

If you do not know the value of partition key and the document does have a partition field , use EnableCrossPartitionQuery property to enable cross partition queries.

Then, query your document by Id and fetch it's SelfLink property. Use this SelfLink value to Delete your document.

Code:

FeedOptions queryOptions = new FeedOptions
        {
            MaxItemCount = 10,
            EnableCrossPartitionQuery = true
        };
        var id = '1';
        var queryString = "SELECT * FROM c WHERE c.id= '" + id + "'";
        var queryInSql = documentDbClient.CreateDocumentQuery<Document>(
                               "uri",
                               queryString,
                               queryOptions).AsDocumentQuery();
        var document = await queryInSql.ExecuteNextAsync<Document>().ConfigureAwait(false);

        //Delete a document using its selfLink property
        //To get the documentLink you would have to query for the Document, using CreateDocumentQuery(),  and then refer to its .SelfLink property
        await documentDbClient.DeleteDocumentAsync(document.AsEnumerable().FirstOrDefault().SelfLink);

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