I’m sure you’ve encountered the scenario where you need to add multiple AND or OR statements to an NHibernate query. The string parsing and manipulation required to do it in HQL would be enough to send you straight to programmer hell. So it turns out the easiest (in my opinion) option is to use the good ol’ Criteria API. But it’s not as obvious as it first seems. In order to accomplish the task, you actually need to use a pair of constructs that may be new to you: Conjunction which represents a grouping of AND statements (A and B and C…); and Disjunction, a grouping of OR statements (A or B or C…). Here’s an admittedly contrived example of how you could query for Persons by FirstName that are not archived (IsArchived), ordering by FirstName:
This would generate something similar to the following SQL-statement:
If you needed ANDs instead of ORs you would use Conjunction instead of Disjunction.
A more powerful example would be if you needed multiple sets of statements. Consider the following scenario:
Select all Persons where IsArchived is false and the FirstName is “Nick”, or all Persons where IsArchived is true and the FirstName is “Bryan”
Here’s how you would do it using Conjunctions and Disjunctions:
Which would produce the following: