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: Int32 (0)]

SELECT Count(id)
FROM benefit
WHERE employee_id =@ p0;
@p0 = 13 [TYPE: Int32 (0)]

Instead of loading all benefit instances into memory, NHibernate smartly issues a SELECT COUNT() statement which defers the operation of counting the records to database server. We not only reduce in-memory processing of records but also save on the amount of data returned from the server.

Another advantage extra lazy behavior brings about is to do with indexed collection. We do not have any examples of indexed collection in our domain mode. Items of an indexed collection can be accessed using integer indices. Because NHibernate knows about those indices, NHibernate can issue a SQL only to load the item that you have accessed, instead of bringing in the whole collection and wasting time on processing loads of data that you are not accessing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.136