A
A
Alexander Nikulshin2021-05-11 11:06:31
ASP.NET
Alexander Nikulshin, 2021-05-11 11:06:31

How to fix JsonException error when getting data in api controller from EntityFramework database?

When requesting from the database through EntityFramework on asp core (net platfrom 5), an error occurs:

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.


Data is taken from models:
list of products
public class Good
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Article { get; set; }
        public string BarCode { get; set; }
        public Units Unit { get; set; }
        public decimal Price { get; set; }
        public List<GoodPrice> GoodPrices { get; set; }
        public List<CheckGood> CheckGoods { get; set; }
    }

price list
public class GoodPrice
    {
        public int Id { get; set; }
        public int GoodId { get; set; }
        public Good Good { get; set; }
        public int ShopId { get; set; }
        public Shop Shop { get; set; }
        public decimal Price { get; set; }
    }


The api controller itself and the Get method that throws an error
[Route("api/[controller]")]
    [ApiController]
    public class GoodsSynchController : ControllerBase
    {
        public IConfiguration configuration;
        public ILogger<GoodsSynchController> logger;
        public shopContext db;
        public GoodsSynchController(IConfiguration configuration, ILogger<GoodsSynchController> logger, shopContext db)
        {
            this.configuration = configuration;
            this.logger = logger;
            this.db = db;
        }
        [HttpGet("{idShop:int}")]
        public async Task<IActionResult> Get(int idShop)
            => Ok(await db.Goods.Include(g => g.GoodPrices.Where(p => p.ShopId == idShop)).ToListAsync());
    }


609a3af6db945504381363.png
Please help fix this error!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2021-05-11
@xasya89

services.AddMvc.AddJsonOptions(o => {
o.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
o.JsonSerializerOptions.MaxDepth = 0;
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question