I have an MVC-3 (RC1) application using Entity Framework 4.
I wish to return a JSON object from a controller action. This object is referenced by other objects, which obviously return the reference.
I thus receive the following circular reference error:
Server Error in '/' Application.
A circular reference was detected while serializing an object of type 'Application.Models.ReferenceObject'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'Application.Models.ReferenceObject'.
NB: Application & ReferenceObject are obviously replacements for the actual namespace / object.
According to Stack Overflow: Circular reference exception when serializing LINQ to SQL classes, this can be overcome using JSON.Net; however I would like to avoid this and instead try to exclude the offending reference properties from the object being serialized.
What do I mean?
I want to do something like this:
IList<ReferenceObject> list = Repository.GetReferenceObjects();
return Json(list.**<method>**("ObjectsReferencingThis"));
where **<method>**
is some method that does the opposite to the ObjectQuery(Of T).Include
method and ObjectsReferencingThis
is the property that is causing the circular reference.
NB: I do not wish to remove these properties or create POCOs as this only affects the Json serialization.
Anyone able to help please?
:)
I had a similar problem when worked on one of my previous project. Here is what I ended up doing:
Here is how the result Json would look like:
}
You can also add any other properties from you referenced objects to the result as you wish,to be shown in your Json object :)
I made a very trivial solution which is not recommended if you have very big list
the problem of
circular reference
in my case is in LetterStatus.Letters so IIterated through the list
andassigned it to null
as I told you its
not recommended
if you havevery big list