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();

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

return criteria.List();

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.