I am trying to return JsonResult
using MVC controller standard Json(object)
method. My object of type Model1
is built by Fluent NHibernate.
Model1
has property of type Model2
. In debug mode I see that the environment creates a proxy descendant class of Model2
called Castle.Proxies.Model2Proxy
. This is used internally by Fluent Nhibernate, I believe, to satisfy my mappings. And in run time, actual model1.Model2 is of type Castle.Proxies.Model2Proxy
.
The problem is that when my Model1
is serialized, Model2
is being serialized too. And the serializer seems to try to serialize all the properties of this object, including those generated by Castle and not needed by me. I would be OK with it if it did not cause an exception. Namely, somewhere inside this object a circular reference presents and the exception is caused by it. Here is the exception text:
System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
I double checked my domain and found no circular references there, so I am blaming Castle. Am I correct? Is Castle really to blame for that? If so, what are my options? How do I tell serializer to ignore Castle properties? Particularly, how do I tell it to serialize the defined type, not the actual one?
I tend to covering my domain models with ViewModels to fight this issue, which is a recommended approach, but I would really love to know another cure, if it exists.
Model2
have a reference to its parent,Model1
by any chance?Type
object somewhere down the hierarchy, which hasRuntimeModule
reference. And the module, naturally, contains a reference to thisType
in a collection of all types contained within this module.Model2
, not he proxy. I will verify. I am not sure, however, that I want eager loading in my scenario.