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.
in general, it’s not good practice to serialize your model entities.
this is because you want to have complete control over what you serialize and send to the client.
when you serialize your model entities, you might be serializing the whole object graph associated with them, which you don’t necessarily need / want.
(for example- if you want the user to view just a
Model1entity, you might be sending along also aModel2entity, along with itsModel3collection etc.)the standard way to deal with it is using some sort of DTOs, which are adapted to display precisely what you want to display. for example: