Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

October 2011 - Posts

NHibernate Pitfalls: Lazy Entities and Virtual Members

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

If you want to lazily load an entity as part of a many to one or one to one endpoint, you must declare it as lazy. This way, a proxy can be generated for it, by subclassing it:

   1: mapper.Class<Customer>(ca =>
   2: {
   3:     ca.Table("`CUSTOMER`");
   4:     ca.Lazy(true);
   5:     //rest goes here
   6: }

NHibernate’s built-in proxy factory requires that all properties and methods be declared virtual, not just the mapped properties, so keep this in mind.

If you want to change this behavior, you can either disable proxy validation:

   1: NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration()
   2: .SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString)
   3: //rest goes here

Or you can make all properties and methods virtual and either public, protected or protected internal - internal and private won't do.

More Posts