24

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

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Vinblad
  • 676
  • 1
  • 7
  • 18

3 Answers3

55

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)
)
James Gregory
  • 14,173
  • 2
  • 42
  • 60
17

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);
savemaxim
  • 377
  • 3
  • 6
3

You could use Restrictions.or, such that:

session.CreateCriteria(typeof(someobject))
    .Add(critiera)
    .Add(other_criteria);

where:

other_criteria = Restrictions.or("property", "value");

You can learn more about this following the Criteria Interface documentation of Hibernate, which is the same as NHibernate.

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152