Ramon Smits

Tell me your secrets and i'll tell you mine

Recent Posts

Tags

Community

Email Notifications

Patterns & Practices / Guidelines

EntLib

Nant

Blogs that I monitor

Archives

April 2010 - Posts

How to perform a not equals comparison with NHibernate criteria api

I often hear that NHibernate is not usable for selecting records as it is not possible to perform a not equal comparison with the criteria api. I must admin that it took me a while before I found out but it really is more logical when you know. Lets take a look at the following example:

// Select entries where name = "Ramon"
var criteria = DetachedCriteria.For<MyCoolClass>()
.Add(Restrictions.Eq("Name", "Ramon"));

Your first reaction it to find the opposite of Restrictions.Eq but then you are amazed that it does not exists. The solution is so simple that it will almost embares you:

 

// Select entries where name != "Ramon"
var criteria = DetachedCriteria.For<MyCoolClass>()
.Add(!Restrictions.Eq("Name", "Ramon"));

 

Do you see the difference? I added an exclamation mark before Restrictions.Eq to invert the restrictions operator.

So now you know and probably never forget ;-)