views:

990

answers:

1

Hi,

How do I serialize entity framework object into JavaScript Object (JSON)? I tried using JSON.NET but I am getting the following exception when I try to serialize it.

Exception: Newtonsoft.Json.JsonSerializationException, Message="Self referencing loop"

Hitesh

+1  A: 

It sounds like you are having the same general problem as the original DataContract serializer, in regards to cyclic references. While objects referencing each other is fairly common with object graphs in memory, such cyclic references inevitably result in infinite recursions when serialized if the serializer does not specifically account for it. There are few, if any, established standards for dealing with cyclic references in the common non-binary serialization formats (XML and JSON being the two most prevalent.)

Microsoft solved the cyclic problem for the DataContract serializer in .NET 3.5 SP1 by making use of the ref semantics in xml. To my knowledge, there is no such thing for JSON, which might be why JSON.NET is preventing you from serializing your object graph.

I would make sure you have only references in your object graph that are navigable one-way, rather than both ways (i.e. only from parent to child, not from child to parent.) Those parent/child and child/parent are the most common types of cyclic references. It may also be that a lower-level child is ultimately referencing the root of the graph, causing an indirect cyclic graph to be created (these tend to be far less common than the parent/child loops, however.)

Once you eliminate any cyclic references in your object graph, you should be able to serialize.

jrista
Thanks for your answer. I didn't want to eliminate any cyclic references in the object graph as I am not entirely sure how to do it and what would be the implications of making this change. Instead I created plain simple objects and populated these objects using Entity Framework objects and then Serializing the plain objects and it works fine.
Hitesh
Generally speaking, its actually a good practice to keep your domain entities and your DTO's independent of each other. Entities in their native, rich, graph state are a great way to model a business problem domain and solve business problems, but they don't lend themselves well to service-orientation and serialization. My personal preference is to keep my domain as rich and interrelated as possible so it models the business, and provide independent service API's that provide individual serializable DTO's.
jrista