In my opinion, the best way to write queries with NHibernate is to use a criteria object. The ICriteria
object is created from a session, using the syntax Session.CreateCriteria<T>()
or Session.CreateCriteria(Of T)()
. By passing in a type, we basically tell NHibernate what type of objects we will be querying. For example, the following code:
ICriteria criteria = Session.CreateCriteria<Contact>();
would evaluate to a pseudo-SQL query of:
SELECT * FROM Contact;
Once we have an ICriteria
object built, we can simply ask it to retrieve the requested records for us. If we want it to return a list of objects, in this case, a list of Contact
objects, we simply call criteria.List<T>()
or criteria.List(Of T)()
.
IList<Contact> contacts = criteria.List<Contact>();
If we expect our query to return a single record and to return NULL otherwise, we can tell NHibernate to return a UniqueResult<type>()
.
Contact contact = criteria.UniqueResult<Contact...