7

I have a set of linq to sql classes and serialized them into JSON using the .NET JavaScriptSerializer.

However, as soon as I add record onto a relating table, serialization throws a "Circular reference exception". Aaarggh!

It's described in detail here.

I have a few options

  • Convert the linq to sql class to a class with no relationships thus avoiding the circular reference
  • snip the circular reference by nulling associations - i don't consider this to be a real option
  • Use ScriptIgnoreAttribute (somehow). I couldn't easily apply this because the properties are in generated classes and LINQ to SQL doesn't automatically honor buddy classes
  • Use JSON.NET and somehow use attributes + buddy classes to stop the serializer trying to walk across relationships.

Has anyone else encountered this? I would really prefer the last option if possible but I don't know how to do this.

Any help is greatly appreciated

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
CVertex
  • 17,997
  • 28
  • 94
  • 124

3 Answers3

8

The latest version of Json.NET supports serializing circular relationships. Check out Preserving Object References in the help.

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • 2
    Wrote a blog post detailing the setup: http://www.johnnycode.com/blog/2012/04/10/serializing-circular-references-with-json-net-and-entity-framework/ – John B Apr 11 '12 at 13:16
4

Additional link for accepted answer

Json.NET Help, Preserving Object References (with example)

It seems it works fine with LINQ to SQL

Emir
  • 1,586
  • 3
  • 16
  • 32
1

James's solution solved part of my problem. I needed to exclude certain List Types within the object. To solve my problem, I just copied the parts of the object I needed. The following is an example.

var DB = new DBDataContext();
            var lUsers = new List<User>();
            DB.Users.ToList().ForEach(x => lUsers.Add(new User()
                {
                    ID = x.ID,
                    FIRST_NAME = x.FIRST_NAME
                }) );
Spencer
  • 319
  • 5
  • 10