Tutorial :How do I strongly type criteria when using NHibernate's CreateCriteria method?


I'm currently using NHibernate, for the first time, with Fluent NHibernate. I've gotten everything setup nicely, however now I've come to actual doing some data retrieval, it seems to have fallen short.

I was expecting NHibernate, to allow me to do something like:

session.CreateCriteria<TblDocket>()      .Add(Restrictions.Eq(x=> x.DocketNumber, "10101"));  

However, this doesn't appear to be the case and I seem to have to write:

session.CreateCriteria<TblDocket>()      .Add(Restrictions.Eq("DocketNumber", "10101"));  

That'll be less-than-wonderful when I rename any properties! I've always though hard coded strings in code is bad, especially when the strings relate to property names.

Is there any way I can strongly type these restrictions? I had a look at this blog post, but it seems quite messy, is there a nicer solution?


I decided to use NHibernate.Linq instead. I found a brilliant tutorial here.


You can't using out-of-the-box NHibernate. There is a project called NHibernate Lambda Extensions which allows you to do this with some limitations.


since NHibernate 3.0 there is also QueryOver available which are a nice typesafe wrapper around the criteria API.

session.QueryOver<TblDocket>()      .Where(x => x.DocketNumber, "10101");  


For anyone who comes along this post and doesn't like linq or isn't too familiar with lambda you can still safely use ICrierta's such as

session.CreateCriteria<TblDocket>().Add(Restrictions.Eq("DocketNumber", "10101"));  

what you need is helper classes so you can remove the magic strings such as "DocketNumber" so that if you do change your property names or column names these are taken care of for you or will atleast produce a build error so you know before you publish your code. Anyone wanting to see an example can have a look at NhGen ( http://sourceforge.net/projects/nhgen/ ) and the query examples at https://sourceforge.net/projects/nhgen/forums/forum/1169117/topic/3789112 which show how helpers classes can be used like.

// Find using a simple entity query   IList<IMessage> messageList3 = messageDao.Find( new [] { Restrictions.Le(MessageHelper.Columns.Date, dateLastChecked) } );   

Note that this project also created entity wrapper classes which group all your common CRUD methods into one class (xxxDao as show above) so you don't have to keep copying the same code over and over again.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »