NHibernate – generating WHERE IN … OR … queries

Let’s assume that we have a simple table GL_Task which looks like this
Table
I was asked to rewrite simple SQL query

using NHibernate’s QueryOver API. As simple as it may seem, solution for this particular problem is not straightforward. My first (not so clever) attempt was simply combining WhereRestrictionOn and Where clause

Of course this query returns wrong data because of the fact, that NHiberante by default “joins” queries using AND operator. So above query will result in generating something like that

After a little digging I managed to write appropriate query

Although this code generates correct SQL, it is hard to use it in case of many OR statements. For example, adding one more OR force us to write

In my opinion this is a little bit hard to read, so I continued my searching to find more elegant solution. My third attempt was based on Restrictions.Disjunction

This was almost perfect solution. Adding new OR statements do not require us to do function nesting

However the ultimate solution is to just add NHibernate.Criterion namespace and use IsIn extension method. This operation simplify our query into single lambda expression

Source code for this post can be found here

NHibernate – generating WHERE IN … OR … queries