Using extra-lazy for lazy collections

Extra lazy behavior was mentioned in the previous chapter. It is worthwhile to mention two benefits that extra lazy behavior brings to the table.

Suppose you have loaded a bunch of employees from database to be displayed on UI, along with number of benefits that they are entitled to. When you call employee.Benefits.Count() as in the following code, NHibernate would load the Benefits collection into memory and then count the number of items:

var employees = Database.Session.Query<Employee>()
.Where(e => e.ResidentialAddress.City == "London");

foreach (var employee in employees)
{
  Assert.That(employee.Benefits.Count(), Is.GreaterThan(0));
}

But if you enable extra lazy behavior on mapping of the Benefits collection ...

Get Learning NHibernate 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.