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:
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?8 Replies
You can also use DTO's or specify a max depth in JsonSerializerOptions
Map to DTOs. Its the only real answer.
You can't treat your domain models as viable serialisation targets, it causes a whole bunch of issues, including oversharing and cyclic object reference
I also saw ReferenceHandler.IgnoreCycles if you don't want the metadata of the referencing
Got it to work with Dtos! This is how it looks
Quite the lesson because I had no idea how Queryables worked, I thought it was like regular linq, but it's actually building the query
So I ended up with the impression that the error came up right at the Include, and had no idea you could Select after
Nested a bunch of Dtos and ended up with what I wanted:
Thank you very much!
looks good
if the Queryable uses the includes, you can usually leave them out btw