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 then the preceding code would result in the following SQL being sent to database:
SELECT Count(id) FROM benefit WHERE employee_id =@ p0; @p0 = 11 [TYPE: Int32 (0)] SELECT Count(id) FROM benefit WHERE employee_id =@ p0; @p0 = 12 [TYPE...