Blankman
Blankman

Reputation: 267040

How to do a NotEqual to in NHibernate

I have an enumeration of type int in my entity, UserStatus.

I want to get all users where the UserStatus <> Cancelled.

So:

Session.CreateCriteria(typeof(User))
.Add(Expression.Eq("UserStatus", (int)UserStatus.Cancelled)
.UniqueResult<User>();

The above is fore equal, I need to get not equal.

Upvotes: 18

Views: 11821

Answers (2)

Ben
Ben

Reputation: 2033

.Add(!Restrictions.Eq(propertyName, value));

Upvotes: 3

zoidbeck
zoidbeck

Reputation: 4151

With thanks to Alex use this for NH2 and up:

Session.CreateCriteria(typeof(User))
.Add(Restrictions.Not(Restrictions.Eq("UserStatus", (int)UserStatus.Cancelled))
.UniqueResult<User>();

For older Versions this would be:

Session.CreateCriteria(typeof(User))
.Add(Expression.Not(Expression.Eq("UserStatus", (int)UserStatus.Cancelled))
.UniqueResult<User>();

Upvotes: 45

Related Questions