Refactorable NHibernate Criteria

When you use NHibernate Criteria API in traditional way, you have to pass property names as strings. Unfortunatelly that makes your code unrefactorable - when you change something in your mappings, you have to check whether your code still works!

// build criteria in traditional way
DetachedCriteria criteria = DetachedCriteria.For()
    .Add(Expression.Or(Expression.Eq("FirstName", "John"),
                       Expression.Gt("Salary", 700)))
//and executing criteria
object queryResult = criteria.GetExecutableCriteria(session).List();

Using Criteria builder you can express every Recorder property as NHibernate Criteria, what makes your code stable and fully-refactorable. When you change someting in DTO classes, compiler will show you the affected code!

// build criteria with NHCB support
EmployeeRec employeeRec = new EmployeeRec();
DetachedCriteria criteria = DetachedCriteria.For()
//and executing criteria
object queryResult = criteria.GetExecutableCriteria(session).List();

NHibernate Criteria Builder is build on NHibernate Criteria API, so you can't go any further than Criteria API goes. If you don't know how to express your businnes restrictions in the Recorders way, you can always use this technique.

Last edited Jan 18, 2009 at 5:26 PM by infomechanica, version 5


No comments yet.