In delving into Fluent nHibernate, I discovered a potential breaker for using it...
Given the following POCO code.
public class Customer
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Details Details { get; set; }
}
public class Details
{
public virtual int Id { get; set; }
public virtual IList<Orders> Orders { get; set; }
}
public class CustomerMap : ClassMap<Customer>
{
// perform mapping
}
public class DetailsMap : ClassMap<Details>
{
// perform mapping
}
I loaded up ASP.NET MVC and attempted to use Json Serialization.
using System.Web.Script.Serialization;
public static partial class JsonExtensions
{
public static string ToJson(this object item)
{
return new JavaScriptSerializer().Serialize(item);
}
}
And Lo, when I passed a query from my nHibernate context to the ToJson
method, I got an error!
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.
It seems to do this whether I pull a single object, or a list of objects ..or anything for that matter. I've even tried marking my classes as [Serializable]
with the same result. This doesn't happen with the exact same classes using the Microsoft Entity Framework Code-Only approach.
Can I not deserialize nHibernate DTOs into JSON?
Adding more code for examination.
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var customers= session.CreateCriteria(typeof(Customer)).List<Customer>();
foreach (var customer in customers)
{
Console.WriteLine(customer.ToJson());
}
Console.ReadLine();
}
}
This is just a hunch but you might like to investigate what type it is really trying to serialize- nHibernate generates proxies for each POCO at runtime (so it can do stuff like lazy loading of foreign key entities, etc.). This may be why you are getting this error.
Try specifying the exact type to be serialized or perhaps create a brand new object to serialize, populating its properties with that of the nHibernate POCO.
EDIT: This seems to be much more likley the answer to your problems:
http://www.west-wind.com/WebLog/posts/147218.aspx
Basically, check all of your POCO's for any circular references (e.g. a Customer POCO that has an Order POCO as a property while the Order POCO has a list of Customer's as a property)