2010-01-14 15 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

相关问题