Answer the question
In order to leave comments, you need to log in
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.
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; }
}
[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());
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question