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