In this post we are going to search using ICriterion to filter and sort the results. The only pre-requisite is that you properly configure your nHibernate environment, and like all my other code samples, know c#.
This one is pretty easy, first we are going to set the required references:
using NHibernate; using NHibernate.Criterion;
Then we are going to define the ICriterion array. In this example, were are going to search for contacts that:
- Belonging to the logged on owner (OwnerID variable).
- LastName starts with some string entered by the user (LastNameValue variable)
- Were added after a specific date chosen by the user (StartDate variable)
For the LastName like search, nHibernate gives us some options in the MatchMode enum: Anywhere, End, Exact, Start. In the snippet below, you will notice I went with Start.
Finally, we are going to sort the results by LastName, then FirstName.
ICriterion[] query = {
Expression.Eq("OwnerID", OwnerID),
Expression.Like("LastName",LastNameValue,MatchMode.Start),
Expression.Ge("CreationDate",StartDate) };
Order[] order = {
Order.Asc("LastName"),
Order.Asc("FirstName")};
Contact[] results = contact.FindAll(order, query);
That’s it!
Related articles:
- Performing an ActiveRecord SimpleQuery search




