dev1111
dev1111
CC#
Created by dev1111 on 8/20/2024 in #help
System.Text.Json.JsonException: A possible object cycle was detected
I'm working on an API and I have Doctor and Appointment models. The Doctor model has a List<Appointment> as a prop and Appointment has a Doctor prop too. I understand what's going on but couldn't find a solution for it yet: when I fetch a doctor and Include(doc => doc.Appointments), it seems like, since the Appointment could have a reference to that same Doctor (and it does), they would end up including each other infinitely. The thing is, if I add a [JsonIgnore] to the Appointment's 'Doctor' property, things start working (since the Doctor won't be present among Appointment's properties) but it won't be serialized when I'm fetching Appointments, even with Include(appt => appt.Doctor). Another odd thing is that Doctor is not added automatically when I fetch an Appointment, but it still complains when Include(doc => doc.Appointments) even though I'm not doing ThenInclude(appt => appt.Doctor) right after. The error code:
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. Path: $.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.User.
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. Path: $.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.Appointments.Doctor.User.
The ReferenceHandler.Preserve made it work but it adds $id and $values to the json object and, at first, seemed like a hack (I'm ok with it in case it's not). Any ideas?
12 replies