Serializing Entity Framework Objects into JSON

If you want Serialize Entity Framework Objects into JSON, You can use JSON.NET from http://www.newtonsoft.com. to do this, install JSON.NET from nuget and use following code sample:

return Newtonsoft.Json.JsonConvert.SerializeObject(results, Formatting.Indented, 
new JsonSerializerSettings { 
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
});

ReferenceLoopHandling.Ignore can prevent circular reference error.


It sounds like EF is not giving you a ASSystem, but rather some subtle dynamic subclass of that with some EF goo. If that is correct, I would argue the simplest thing to do here is to use something like AutoMapper to get a non-EF copy (into a new ASSystem() instance, untouched by EF). However, a few alternatives:

  • you could try marking ASSystem as sealed, taking away EF's ability to inject itself
  • you you write a custom converter and register it - this is probably more work than mapping, though

You can create a POCO object that can contains your data and can be serialized. For example define:

public class MySystem {
  public int SID {get; set;}
  public string Description {get; set;}
  public string SystemName {get; set;}
}

in your code use this statement:

IQuerable<MySystem> sysList = from s in ctx.AS_SYSTEM where s.SYSTEM_ID == query 
                           select new MySystem(){SID = s.SYSTEM_ID,  
                           Description = s.Description, SystemName = s.SystemName   };
MySystem sys = sysList.First();

Now you can serialize sys as in your example.