11

I'm trying to serialize an nhibernate entity in to json but I always get this error saying Cannot serialize a Session while connected? Does it has something to do with nhibernate proxy?

ryudice
  • 36,476
  • 32
  • 115
  • 163

2 Answers2

15

I started getting the same error when I switched from System.Web.Script.Serialization.JavaScriptSerializer to Newtonsoft.Json.

Using the contract resolver from this answer fixed this problem:

string output = JsonConvert.SerializeObject(theObject,
                new JsonSerializerSettings()
                {
                    ContractResolver = new NHibernateContractResolver()
                });
Community
  • 1
  • 1
Zar Shardan
  • 5,675
  • 2
  • 39
  • 37
7

Yes, this is related to lazy loading. You will need to configure NHibernate to eagerly fetch associations if you want to be able to JSON serialize it. But I would recommend you using view models instead. Ayende Rahien blogged about this issue.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928