How to create OR statements for NHibernate?
When creating a criteria for NHibernate all criteria are added as AND
.
For instance:
session.CreateCriteria(typeof(someobject))
.Add(critiera)
.Add(other_criteria)
then end result will be
SELECT ...
FROM ...
WHERE criteria **AND** other_criteria
I would like to tell NHibernate to add the criterias as "OR"
SELECT ...
FROM ...
WHERE criteria **OR** other_criteria
Any help is appreciated
Solution 1:
You're looking for the Conjunction
and Disjunction
classes, these can be used to combine various statements to form OR and AND statements.
AND
.Add(
Expression.Conjunction()
.Add(criteria)
.Add(other_criteria)
)
OR
.Add(
Expression.Disjunction()
.Add(criteria)
.Add(other_criteria)
)
Solution 2:
Use Restrictions.Disjunction()
var re1 = Restrictions.Eq(prop1, prop_value1);
var re2 = Restrictions.Eq(prop2, prop_value2);
var re3 = Restrictions.Eq(prop3, prop_value3);
var or = Restrictions.Disjunction();
or.Add(re1).Add(re2).Add(re3);
criteria.Add(or);