❔ Serializing related object EF
Hello all,
I have 2 models
And I would like to include
Coordinates
of City
in my response however I get error 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 64
My query is
I have googled it and found different approaches but from the examples I saw, this should be working.
Why does this happen?28 Replies
Well, City references Coordinates and Coordinates reference the City
So we do have an endless loop
.Select()
into a DTO instead of .Include()
ing
The same ringts true for all cases
Even ones without cyclic dependenciesI see, I got confused because every tutorial has a different approach of declaring relation
You could even flatten it too, since it's a 1:1 relationship
If it's supposed to be a 1:1 relationship, then it's declared correctly
Yes it is 1 to 1
What many tutorials fail at, however, is they all use
.Include()
instead of .Select()
ing into DTOsso what am I supposed to do here?
so, select?
Yes
for example
there are some differences but even in official docs they use
include
Tutorial: Read related data - ASP.NET MVC with EF Core
In this tutorial you'll read and display related data -- that is, data that the Entity Framework loads into navigation properties.
not the same
from docs
Probably because it's a doc about loading related data
While
.Select()
is a projection
And it also loads related datameaning?
Well, a chapter in the math book about addition won't cover multiplication
Even if 2 + 2 + 2 + 2 could be better represented as 2 * 4
So
Select
is annotation?huh?
No?
ah I see you are also flattening it as you said
It's a LINQ method that projects each element of an enumerable to a different thing
what about without flattening?
Preserve the nested structure?
Yep
Yep that worked,
What changes do I need to make my model so
this query works? Or is this wrong anyway?
I'm not sure it can work, because of the cyclic dependency
You'd have to either remove the reference to city from coordinates
Or the reference to coordinates from city
I will try
yes now it works
I removed
City
from Coordinates
I have seen some examples where related model is declared as virtual
What does virtual do in this case? Which one is correct?It's for lazy loading
Don't use lazy loading
I see, thanks a lot for your help
Also, don't return your database entitites directly
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.