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

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

 

 

Comments

SumitG said:

Thanks, that was helpful and not at all embarrassing :)

# May 12, 2010 4:50 PM

Rico said:

Somewhat embarrassing here :)

But definitely, thanks. Hibernate has spoiled us with .ne()

# August 5, 2010 9:08 PM

S said:

I think this is pretty unreadable, I would have much preferred a seperate restriction!

# October 8, 2010 12:23 PM

Praveen said:

Thanks alot. I have been breaking my head for this for couple hours. You made my day :)

# March 8, 2011 11:25 PM

PandaWood said:

Thanks, I'd typed:

.Add(Restriction.Not(Restrictions.Eq("Name", "Ramon")));

Before discovering your advice... btw it didn't work.

# May 17, 2011 3:29 AM

Vamsi said:

Thank you.

# August 3, 2011 11:52 AM

Vinay said:

Thanks a lot:)

# June 18, 2012 8:42 AM

Yael said:

Ahhhhhh!!!!

Excelente!!!

# August 14, 2012 4:34 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 7 and 4 and type the answer here: