Friday, June 25, 2010

Lazy Load This!

Or rather - "Lazy Loading can cause problems with C# code"

Here was my dilemma:


class Foo
{
public virtual Bar bar {get; set;}
}


Had the Fluent NHibernate ClassMap:


class FooMap : ClassMap<foo>
{
References(x => x.bar).ForeignKey();
}



No problem right? Well it was working fine until I tried to serialize the result using MVC Contrib's XmlResult object. Kaboom! It took me many hours to figure out that the serializer was trying to use the proxy class to Bar instead of Bar itself.

The solution was to modify the FooMap to not lazy load like this:


class FooMap : ClassMap<foo>
{
References(x => x.bar).ForeignKey().Not.LazyLoad();
}


This could probably lead to performance problems in production - so if you do turn off the default lazy loading behavior, ensure you're using a product like NHProf or a SQL Profiler to monitor what your ORM is doing.

No comments: