Linq to SQL and Serialization : A circular reference was detected while serializing an object of type [whatever]
Posted by andrewmyhre on November 4, 2009
Okay so I created a Linq to SQL model today. It includes tables for Blog Posts and Blog Comments which have a one-to-many relationship, hence a BlogComment has a .BlogPost property and a BlogPost has a .BlogComments property. Pretty standard.
When I attempted to serialize a collection of BlogPosts and their related BlogComments I was met with the following error:
A circular reference was detected while serializing an object of type BlogPost.
Fairly obvious why – the serializer is working through each property on a BlogPost using reflection, then enumerating each comment on the blog post, enumerating each property on the comment which includes a reference back to the blog post – which is where the circular reference joins up.
Obvious problem, but how to get around it? What I actually need to do is instruct the XmlSerializer to ignore the BlogComment.BlogPost property – I want it to enumerate the comments attached to a blog post but I don’t want it to walk back up to the blog post. To accomplish this I don’t want to have to mess with my DBML file or the C# class definitions, because as soon as I modify the database in the future I’ll have to reimplement those changes. A partial class implementation won’t help me because I need to modify the original class, not patch new functionality onto it. I was thinking I needed to add an [XmlIgnore] attribute somewhere, and that this would be a nightmare.
Well it turns a much simpler solution is to just mark the relationship as an Internal property in the Linq to SQL designer.
This works because the XmlSerializer only serializes public properties.

Chris said
Nice tip!
I was investigating a similar problem very recently… if only you’d posted last month!