2010-01-14 20 views
2

如何分組NHibernate中的表達式集?例如,我想我的篩選查詢,像這樣:如何在NHibernate中對錶達式進行分組?

(ShowOnDate IS NULL OR ShowOnDate <= GETDATE()) AND (ExpirationDate IS NULL OR ExpirationDate >= GETDATE()) 

我可以另加4個準則,但我無法弄清楚如何效仿paranthesis分組。謝謝!

編輯,以顯示我的最終解決方案:

  result = this.Session.CreateCriteria<Model.News>() 
       .Add(Expression.IsNull("ExpirationDate") || Expression.Gt("ExpirationDate", DateTime.Now.Date)) 
       .Add(Expression.IsNull("ShowOnDate") || Expression.Le("ShowOnDate", DateTime.Now.Date)) 
       .AddOrder(new Order("SubmittedDate", true)) 
       .List<Model.News>(); 
+0

它尚不清楚這是否問題1與HQL或Criteria API相關。儘管如此,我還是從Criteria的角度回答了這個問題,以備有用。 – 2010-01-15 06:05:34

+0

我的意思是標準......感謝您的回答! – 2010-01-15 16:32:25

回答

4

的標準API提供運算符重載爲||和& &讓您在標準結合起來是這樣的:

 
criteria.Add(
    (Restrictions.IsNull("ShowOnDate") 
     || Restrictions.Le("ShowOnDate", DateTime.Now)) 
    && (Restrictions.IsNull("ExpirationDate") 
     || Restrictions.Ge("ExpirationDate", DateTime.Now))); 

如果你想避免超負荷運營商,那麼你可以使用一起選擇/脫節達到相同的效果(在冗長大幅增加):

 
criteria.Add(Restrictions.Conjunction() 
    .Add(Restrictions.Disjunction() 
     .Add(Restrictions.IsNull("ShowOnDate")) 
     .Add(Restrictions.Le("ShowOnDate", DateTime.Now)))) 
    .Add(Restrictions.Disjunction() 
     .Add(Restrictions.IsNull("ExpirationDate")) 
     .Add(Restrictions.Ge("ExpirationDate", DateTime.Now))))); 
+0

+1不知道重載|| &&。對於此查詢,您可以改用Restrictions.And和.Or。當您需要比較兩個以上的表達式時,Conjuction和Disjunction是適用的。 – dotjoe 2010-01-15 15:39:27

+0

完美。真棒回答。謝謝! dotjoe,你能提供你的建議的代碼示例嗎?我會趕上它。 – 2010-01-15 16:33:32

+0

當然...我會這樣做的10分..lol – dotjoe 2010-01-15 17:08:17

2

還有Restrictions.And和或者當你只需要兩個表達式結合起來......

criteria 
    .Add(Restrictions.Or(Restrictions.IsNull("ShowOnDate"), Restrictions.Le("ShowOnDate", DateTime.Now))) 
    .Add(Restrictions.Or(Restrictions.IsNull("ExpirationDate"), Restrictions.Ge("ExpirationDate", DateTime.Now))); 
+0

新手問題 - 使用像你這樣的限制和像我在我的OP中的表達式有什麼區別? – 2010-01-15 17:17:15

+0

休眠列表表達式作爲半棄用https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Expression.html但這是NHibernate,所以我不知道爲什麼? – dotjoe 2010-01-15 17:24:05

+0

有趣。我認爲表達式是新的,限制是舊的。我必須扭轉局面。我真的需要學習更多...... – 2010-01-15 17:34:40

相關問題