简体   繁体   中英

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

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)
)

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM