tags:

views:

192

answers:

2

How can I group sets of expressions in NHibernate? For example, 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>();
+4  A: 
Aidan Boyle
dotjoe
Perfect. Awesome answer. Thanks! dotjoe, can you provide the a code sample of your suggestion? I will upvote it.
Mike C.
sure...I'll do that for 10 points..lol
dotjoe
+2  A: 

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)));
dotjoe
Newbie question - what's the difference between using Restrictions like you are and Expressions like I am in my OP?
Mike C.
Hibernate lists Expressions as semi-deprecated https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Expression.html but this is NHibernate so I'm not sure why?
dotjoe
Interesting. I thought that Expressions were new and Restrictions were old. I must have got that reversed. I really need to learn a lot more...
Mike C.
dude tell me about...I've been using NHibernate for like 3 months and I keep learning new stuff every day.
dotjoe
We've been using it about the same duration. I done a lot of "easy" stuff with it, but am just now starting to get a little more complex.
Mike C.
Yes me too...I think I learned it backwards because I had the dynamic Criteria queries down before I fully learned the mappings, cascades, change tracking, etc. Anyways, it sure beats the hell out of hand rolled data access!
dotjoe
That's the truth.
Mike C.