Our GetById()
and GetAll()
methods are great, and they do just what we want, but what if we want more? What if we don't want all of the Contacts, but only those that have a first name of "Joe", or birthdays between the 1st of January and 31st of December in 1990? That's where we can use things such as Restrictions
in NHibernate to "trim down" the collection of results.
One of the most common filtering actions is to restrict the result set to a particular value, or a something that contains a particular value. If we wanted to only get Contacts with the first name "Joe", we could create the following query:
ICriteria criteria = Session.CreateCriteria<Contact>(); criteria.Add(Restrictions.Eq(FieldNames.FirstName, "Joe")); return criteria.List<Contact>();
If we wanted everyone who has a first name that starts with "Joe", we could change it to:
ICriteria criteria = Session.CreateCriteria<Contact>(); criteria.Add(Restrictions.Like(FieldNames.FirstName, "Joe%"...