2008-12-22 45 views
19

在爲NHibernate創建條件時,所有條件都被添加爲AND如何爲NHibernate創建OR語句?

例如:

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

那麼最終的結果將是

SELECT ... 
FROM ... 
WHERE criteria **AND** other_criteria 

我想告訴NHibernate的該規定 - 添加爲 「OR」

SELECT ... 
FROM ... 
WHERE criteria **OR** other_criteria 

任何幫助讚賞

回答

48

您正在尋找ConjunctionDisjunction類,這些可用於組合各種語句以形成OR和AND語句。

.Add(
    Expression.Conjunction() 
    .Add(criteria) 
    .Add(other_criteria) 
) 

OR

.Add(
    Expression.Disjunction() 
    .Add(criteria) 
    .Add(other_criteria) 
) 
2

你可以使用Restrictions.or,使得:

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

其中:

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

您可以瞭解更多關於此之後的Criteria Interface documentation of Hibernate,這是一樣的NHibernate的。

13

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