user977154 user977154 - 1 year ago 111
C# Question

"Circular Reference" exception when serializing database object

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download