开发者

Serialize nhibernate entity to json error: Cannot serialize a Session while connected

开发者 https://www.devze.com 2023-03-01 18:21 出处:网络
I\'m trying to serialize an nhibe开发者_开发百科rnate 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

I'm trying to serialize an nhibe开发者_开发百科rnate 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?


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()
                });


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消