Sunday, January 8, 2012

How to use NHibernate's SQLCriterion

I recently needed to use NHibernate's SQLCriterion, but lost some time on finding out how to use it. Once you've found it, it's quite simple actually:


ISessionFactory sessionFactory = GetSessionFactory();
ISession session = sessionFactory.GetCurrentSession();
ICriteria criteria = session.CreateCriteria<Customer>();

var sqlString = new SqlString("{alias}.GroupId = " + groupId);
criteria.Add(new SQLCriterion(sqlString, new object[0], new IType[0]));

return criteria.List<Customer>();

The {alias} is there so NHibernate knows where to put the table name. I'm not so sure about the second and third argument of the SQLCriterion constructor, but in my case, I didn't need them. Just don't pass in null or you'll get an exception.

If you need a more advanced SQLCriterion, check out this post by Remco Ros.

2 comments:

Bruno Yudi Shoji da Cruz said...

Helpful post! Thank you!

Bruno Yudi Shoji da Cruz said...
This comment has been removed by the author.