Prasad Deshkar
Prasad Deshkar

Reputation: 11

Unable to delete a Document from cosmosDB

I am trying to delete a document from cosmosDB (cosmosDB emulator) using c# .Net Core 3.1 based on an id field. For that I am using DeleteDocumentAsync(). It is not throwing any error but is neither deleting the document. When I get the result of operation in a variable then it is showing something like this.

System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: close
Host: localhost:44310
Referer: http://localhost:4300/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
sec-fetch-dest: empty
origin: http://localhost:4300
sec-fetch-site: cross-site
sec-fetch-mode: cors

Following is the code snippet. I have ensured that delete function is receiving the correct id.

    using System.Collections.Generic;
    using System;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using File.Models;
    using Microsoft.AspNetCore.Http;
    using WebAPIDemo.Utilities;
    using System.Net.Mime;
    using Microsoft.AspNetCore.Cors;
    using System.Linq;
    using Microsoft.Azure.Documents.Client;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;

    namespace File.Controllers 
    {
     [Route("api/[controller]")]
     [ApiController]
     [EnableCors]
     public class EmployeeController : ControllerBase
     {        

        IConfiguration config;

         private string EndPointUrl;

         private string PrimaryKey;

        DocumentClient client;

        public EmployeeController(IConfiguration config)
        {
            this.EndPointUrl = config.GetValue<string>("Cosmos:EndPointUrl");

            this.PrimaryKey = config.GetValue<string>("Cosmos:PrimaryKey");

            client = new DocumentClient(new Uri(EndPointUrl), PrimaryKey);
        }


        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public IActionResult Delete(string id)
        {
            IQueryable<Employee> emps;


            FeedOptions queryOptions;

            queryOptions = new FeedOptions { MaxItemCount = -1 };
            try
            {
               var result =  client.DeleteDocumentAsync(UriFactory.CreateDocumentUri("ems", "empdtls", 
    id));             
                return Ok(result);
            }
            catch (Exception e)
            {
                return BadRequest(e);
            }

        }
    }
}

Upvotes: 1

Views: 742

Answers (1)

Negi Rox
Negi Rox

Reputation: 3912

This is the asynchronous method you forget to add Task in delete record and await functionality. Use the below method and call in your delete function.

public async Task Deleterecord(object key)
{
  var result = await _client.ReadDocumentAsync(UriFactory.CreateDocumentUri(dbName, nameof(TEntity), key as string));
  await _client.DeleteDocumentAsync(result.Resource.SelfLink);
}

Upvotes: 1

Related Questions