views:

235

answers:

2

Can anyone tell me if it's possible to add criteria to an NHibernate lazy loaded collection.

For example let's say I have a department that contains employees... I get the department by id and then I lazy load the employees... however lets say there are 1000's of employees and I only want the employees that were hired in the last 30 days.

GetDeptById(1)
   |
   --Lazy load employees (where HireDate >= 7/1/2009)

Seems like I could possibly do this with filters in the mapping file... but can I add some sort of criteria to the lazy load in code?

+1  A: 

You can use a where clause on the collection mapping.

where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving or removing the collection (useful if the collection should contain only a subset of the available data)

https://www.hibernate.org/hib_docs/nhibernate/html/collections.html

g .
+1  A: 

The best way to implement this would be with a filter. Define the filter in the mappings (both entity and the bag) and then before selecting the "department" enable the filter with parameter the date you want.

session.EnableFilter("HireDateFilter").SetParameter("dateParameter", DateTime.Now.AddDays(-30));

You could also leave the mapping as-is and apply a custom defined filter on the lazy loaded collection.

session.CreateFilter(department.Employees, "HireDate >= :dateParameter").SetParameter("dateParameter", DateTime.Now.AddDays(-30));

If the only thing you want to do is apply the restriction, i would prefer the mapping-filter option because that way you can selectively eager-fetch the collection, having this way the object graph in a single select.

If you want to do additional operations (like paging) the CreateFilter would be better although for more complex scenarios a query targeting the Employees would be better imo.

Jaguar