Nhibernate lazy load options

lazy-evaluationnhibernatePROXY

What is the difference between lazy="true" and lazy="proxy" in nhibernate?

Best Answer

I suspect another way of thinking about it would be this.

class Foo
{
   public virtual Bar SingleBar { get; set; }
   public virtual ICollection<Bar> MultiBar { get; set; }
}
  • lazy="proxy" applies to single objects (ie foo.SingleBar)
  • lazy="true" applies to collections of objects (ie foo.MultiBar)

(You can't set lazy="proxy" to a collection, nor can you set lazy="true" to a single reference. Either will cause NH to throw a XmlSchemaException which is a little cryptic to beginners.)

Operationally they do the same abstract thing: when and only when the property is accessed does NHibernate hit the database and populate the property.

There is however a slight difference in the implementation due what is needed to fetch the objects (in the single case, the reference's id (Bar) was loaded with the parent entity (Foo). In the collection case, the ids are unknown and must be found in another table)