Serialize Entity Framework objects into JSON Serialize Entity Framework objects into JSON json json

Serialize Entity Framework objects into JSON


The way I do this is by projecting the data I want to serialize into an anonymous type and serializing that. This ensures that only the information I actually want in the JSON is serialized, and I don't inadvertently serialize something further down the object graph. It looks like this:

var records = from entity in context.Entities              select new               {                  Prop1 = entity.Prop1,                  Prop2 = entity.Prop2,                  ChildProp = entity.Child.Prop              }return Json(records);

I find anonymous types just about ideal for this. The JSON, obviously, doesn't care what type was used to produce it. And anonymous types give you complete flexibility as to what properties and structure you put into the JSON.


Microsoft made an error in the way they made EF objects into data contracts. They included the base classes, and the back links.

Your best bet will be to create equivalent Data Transfer Object classes for each of the entities you want to return. These would include only the data, not the behavior, and not the EF-specific parts of an entity. You would also create methods to translate to and from your DTO classes.

Your services would then return the Data Transfer Objects.


My solution was to simply remove the parent reference on my child entities.

So in my model, I selected the relationship and changed the Parent reference to be Internal rather than Public.

May not be an ideal solution for all, but worked for me.