Wednesday, March 30, 2011

NHibernate FAQ: use the Restrictions instead of the Expression in Criteria queries

Maybe your already know this but the Expression is deprecated since NHibernate version 2. So according to this post you should always use Restrictions in Criteria API queries. Learned this from StackOverflow folks.

For example this old query:
posts = session.CreateCriteria<Post>()
    .Add(Expression.Eq("Id", 1))
    .List<Post>();

Really should be written like this:
posts = session.CreateCriteria<Post>()
    .Add(Restrictions.Eq("Id", 1))
    .List<Post>();

P.S. Then you find an example in internet that uses Expression in Criteria API instead of Restrictions let the author know this or mansion this in comment so that will be less confusion. There are a lot of outdated post that use Expression and peoples get confused by those.