0

When I call

_dbContext.Employees
            .Include(e => e.Company)
            .Where(e => e.IsDelete == false)

I get model Employee with a Company inside, which contains an Employee, and that has a Company and so on - endlessly

This causes an error:

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. Path: $.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee.Company.Employee

Solution with JsonConvert works, but it's not suitable

 ReferenceLoopHandling = ReferenceLoopHandling.Ignore

it is advisable to solve this issue on the EF side

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    *but not suitable* -- Why not? It's your only option, EF is not going to change this *relationship fixup*. Or use DTOs that don't have this circular reference. – Gert Arnold Oct 18 '22 at 09:30
  • because it will affect the other models – Anton Moiseev Oct 18 '22 at 09:40
  • 2
    @CodeCaster Reopened. It's not about lazy loading. It's another common problem (relationship fixup causing circular references) which has other duplicates. – Gert Arnold Oct 18 '22 at 09:45
  • 2
    *because it will affect the other models* -- Then you should project to DTOs and serialize those. Better to do that anyway. I consider this a duplicate: https://stackoverflow.com/q/30186315/861716 – Gert Arnold Oct 18 '22 at 09:46
  • @Gert they ask how to disable "autoincludes" i.e. lazy loading, right? If their question is "how to return DTOs instead of entities" then I agree it's a different question, but that's not what they ask. Edit: ah it is a circular reference due to autofixup, my bad. – CodeCaster Oct 18 '22 at 10:00
  • @CodeCaster Where OP uses the phrase "autoincludes" they actually mean relationship fixup. At any rate, w/o lazy loading the query they show is enough to get circular references. Lazy loading tends to cause other problems in serialization (i.e. an explosion of generated queries, timeouts, memory exceptions). – Gert Arnold Oct 18 '22 at 10:05
  • Add AsNoTracking(), it will solve the issue – Fitri Halim Nov 11 '22 at 12:06

0 Answers0