Search code examples
c#.netdatabasedbcontextdevart

Devart Error when I return database object with IActionResult


I am trying to return the database object that I get from my service in an IActionResult API Call (c# web API project). Whenever I attempt to do that I get this error:

System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Here is my API code that is throwing this:

        [HttpGet]
        [Route("content")]
        public IActionResult GetAllContent()
        {
            try
            {
                List<Content> allContent = _contentService.GetAll();
                return Ok(allContent);
            }
            catch (Exception ex)
            {
               //Log something here
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

I could easily mitigate the error by parsing through the content and creating a dynamic object, but I find it annoying to do whenever I want to return a database object when I'm using the Devart Database Context.

Edit: Further piece of the error message is this:

$.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.PortalCodeMappings.Content.ContentId.

And I understand the circular reference here, is there a way to tell devart I only want the Content section of this without doing something like this:

allContent.Select(x => new { ... });

Edit: I am using Devart Entity Devloper to generate my models and the dbcontext. I do not use Visual Studio or any IDE.


Solution

  • There are two alternative ways to solve the issue:

    1. Use System.Text.Json (de)serialization

    2. Add JsonIgnoreAttribute to one of the navigation property ends

    You can add a custom attribute via the interface of Entity Developer this way:

    a) navigate to Model > Settings > Attributes > select the System.Text.Json.dll assembly and make sure that JsonIgnoreAttribute is checked in the window below, press OK

    b) select JsonIgnoreAttribute in the Attributes collection of a particular class property