title: XmlSerializer - linq-to-sql - A circular reference was detected while serializing an object of type
body: <p>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:</p>
  
  <p><a href="http://www.west-wind.com/weblog/posts/2007/Sep/02/LINQ-to-SQL-and-Serialization" rel="nofollow">http://www.west-wind.com/weblog/posts/2007/Sep/02/LINQ-to-SQL-and-Serialization</a></p>
  
  <p>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.</p>
  
  <p>Based on another article I read, I also tried attributing all EntitySet with this:
  [System.Xml.Serialization.XmlIgnore]</p>
  
  <p>That didn't work for me either--same error.</p>
  
  <p>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.</p>
  
  <p>Here is my serializer function:</p>
  
  <pre><code>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();
          }
      }
  </code></pre>
  
  <p>If anyone has thoughts on this I would love to hear.</p>