If you are using Code first then avoid using virtual
keyword from User
property in Playlist
Model and Playlist
from Song
model.
Because Playlist
auto load your User
model and thus again your Playlist
is by User
and loop goes on.
"Circular Reference" exception when serializing database object
-
09-07-2023 - |
سؤال
I get an error stating that a circular reference was detected while serializing an object of type. I believe it has something to do with my Database and how I have PK's and FK's set.
public string GetSongs(int playlistId)
{
var songs = (from song in _db.Songs where song.PlaylistId == playlistId select song).ToList();
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(songs); // ERROR MESSAGE HERE
return json;
}
Here is a picture of my DB schema:
المحلول
نصائح أخرى
You have very circular references. Your Users
have PlayLists
, and each PlayList
has a user and also a list of Songs
, each of which be in a PlayList
.
- To serialize
User 1
, you will have to serializePlayList 1
. - To serialize
PlayList 1
, you have to serialize itsUser
, which isUser 1
- To serialize
User 1
, you will have to serializePlayList 1
.
etc.
As has been stated elsewhere, the solution is to not directly expose your data model. What you want to serialize is something that contains the foreign keys, not references to Entity Framework models. So your UserDTO
object might contain an Id, Username, Password, and a list of PlayList IDs, not a list of PlayList
. Each PlayListDTO
would contain an Id, UserId
, and a list of SongId
, etc.