I am trying to use XmlSerializer in my linq-to-sql MVC2 webapp to store complex objects in a database. I’ve been googling and experimenting for the past 3 days and cannot get past this circular reference error. I’ve read many articles with suggestions on how to solve this, and none of them have worked for me. I have especially been trying this tactic because LOTS of related articles link back to this one. So this article seems to be emerging as a popular approach:
http://www.west-wind.com/weblog/posts/2007/Sep/02/LINQ-to-SQL-and-Serialization
I have tried to implement this suggested fix for circular reference problems in linq-to-sql and it just doesn’t work. I have triple/quadruple checked that I’m changing ALL child property access modifiers to Internal, but to no avail. I always get the circular reference error no matter what I do. I recompile after each change of course. I make sure to leave the Parent property access modifier to public.
Based on another article I read, I also tried attributing all EntitySet with this:
[System.Xml.Serialization.XmlIgnore]
That didn’t work for me either–same error.
I’m not using WCF – just linq to sql in a webapp with MVC2. I can serialize non-linq-to-sql objects without a problem, regardless of complexity.
Here is my serializer function:
private static string SerializeToString(object obj)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(obj.GetType(), "");
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj, ns);
return writer.ToString();
}
}
If anyone has thoughts on this I would love to hear.
The circular reference occurs when you have to objects which references each other. These kind of references are not supported by the serializer.
For example: