Как исправить ошибку JsonException при получении данных в api контроллере из бд EntityFramework?

При запросе из бд через EntityFramework на asp core (net platfrom 5) возникает ошибка:
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.


Данные берутся из моделей:
список товаров
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; }
    }

список прайсов
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; }
    }


Сам api контроллер и метод Get который выдает ошибку
[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
Помогите исправить данную ошибку!
  • Вопрос задан
  • 243 просмотра
Решения вопроса 1
yarosroman
@yarosroman Куратор тега C#
C# the best
services.AddMvc.AddJsonOptions(o => {
o.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
o.JsonSerializerOptions.MaxDepth = 0;
})
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы