I started getting this cryptic exception when trying to serialize some NHibernate proxies to JSON via JsonResult in ASP.NET MVC. What is supremely odd about this is that I have been applying this serialization strategy quite a bit and haven’t gotten this exception before — I just “randomly” started getting it.

I checked my object model and there are no inherit circular references in the graph in question. How could this exception be getting raised? I’m not sure, and I still don’t have an answer — but I have a solution (for now).

Turn of Lazy Loading

By just setting ‘lazy’ to false on the types in question the exception went away. Obviously this is a sub-optimal solution in the long run, though.

The “Real” Solution

This is very embarrasing to admit, but the reason this failed was a design flaw in my own app. I was trying to serialize NHibernate objects instead of DTOs. Once I switched to strongly typed models everything Just Worked (TM).

The reason for the exception? Castle (the proxy generator I’m using) adds a whole lot of properties neither you nor I need to know about or be concerned with…but someone with a critical eye (i.e. property-based serializers) would be vaaawwwy confused by what it was looking at. Interesting.