开发者

How do I group expressions in NHibernate?

开发者 https://www.devze.com 2022-12-16 16:38 出处:网络
How can I group sets of expressions in NHibernate?For exam开发者_如何学Gople, I want to filter my query like so:

How can I group sets of expressions in NHibernate? For exam开发者_如何学Gople, I want to filter my query like so:

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

I can add the 4 criterions separately, but I can't figure out how to emulate the paranthesis grouping. Thanks!

EDITED to show my final solution:

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


The Criteria API provides operator overloads for || and && allowing you to combine your criteria like this:

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

If you want to avoid the overloaded operators then you can use conjuction/disjunction to achieve the same affect (with a big increase in verbosity):

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


There is also Restrictions.And and Or for when you only need to combine two expressions...

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

精彩评论

暂无评论...
验证码 换一张
取 消