Невозможно удалить документ из cosmosDB - PullRequest
1 голос
/ 08 апреля 2020

Я пытаюсь удалить документ из cosmosDB (эмулятор cosmosDB), используя c#. Net Core 3.1 на основе поля id. Для этого я использую DeleteDocumentAsyn c (). Он не выдает никакой ошибки, но и не удаляет документ. Когда я получаю результат операции в переменной, он показывает что-то вроде этого.

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

Ниже приведен фрагмент кода. Я убедился, что функция удаления получает правильный идентификатор.

    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);
            }

        }
    }
}

1 Ответ

1 голос
/ 08 апреля 2020

Это асинхронный метод, который вы забыли добавить в задачу «Удалить запись» и ожидаете функциональности. Используйте приведенный ниже метод и вызовите функцию удаления.

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...