Question

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:

enter image description here

Était-ce utile?

La solution

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.

Autres conseils

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.

  1. To serialize User 1, you will have to serialize PlayList 1.
  2. To serialize PlayList 1, you have to serialize its User, which is User 1
  3. To serialize User 1, you will have to serialize PlayList 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top