How to perform a not equals comparison with NHibernate criteria api

By ramon
April 20, 2010
1

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 😉

 

 

Comments: 1

  1. Yael says:

    Ahhhhhh!!!!
    Excelente!!!

Leave a Reply

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

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta