As I pointed in a prior post (here) when trying to learn to harness the power of NHibernate sometimes the ‘simple’ can be a bit daunting at first. For instance how do you create a query with NHibernate that looks a little like the information below?
Where ....
AND
(
( a = x AND b = true )
or
( a = y AND b = true )
or
( a = z AND b = true )
)
This would be actually pretty easy if all you needed to do was have a single Or statement because there is a helper method in NHibernate (Expresssion.Or) which takes in 2 parts. However, what do you do if you need to both have more than 2 parts to your Or statement as well as add in a And clause to each one. Well, you have to break away from the helper methods and go straight to the Restrictions class.
The code below is a snippet which should help to show how you can build a criteria which creates the final sql in the same way as above.
// criteria is an instance of the DetachedCriteria object
var queuedCriterion = new List<AbstractionCriterion>();
// build out each of the 'Or' statements
foreach( var someObject in listOfSomeObjects )
{
var partOneExpression = Expression.Eq( "A", "x" );
var partTwoExpression = Expression.Eq( "B", true );
queuedCriterion.Add( Expression.And( partOneExpression, partTwoExpression ) );
}
// put each of the 'Or' statements into one disjunction.
// this will allow them to be nested on the same level
var orDisjunction = Restrictions.Disjunction();
foreach ( var criterion = queuedCriterion )
{
orDisjunction.Add( criterion );
}
// finally add the full list 'Or' into the main criteria object
criteria.Add( orDisjunction )
As you can see above there is a bit of code needed to create this sql syntax when using the criteria, but it is not too bad (IMO). The more I learn about NHibernate, the more I really start to appreciate its power and flexibility.
Till next time,
Posted
04-21-2009 4:26 PM
by
Derik Whittaker