tags:

views:

200

answers:

4

I'm writing a query using ICriteria that should return only the objects where property "Message" has value (i.e. is not null or empty). Below is the format I'm using.

ICriteria.Add(Restrictions.Not(Restrictions.Eq("Message", " "));
ICriteria.Add(Restrictions.Not(Restrictions.Eq("Message", String.Empty));

Can somebody help me with this? Thank you!

+1  A: 

You might want something like:

ICriteria a = session.CreateCriteria(typeof(A));
a.add(Restrictions.Not(Restrictions.Eq("Message", " "));
a.add(Restrictions.Not(Restrictions.Eq("Message", string.Empty));

Although, your first one isn't really checking null, it's checking a single space.

taylonr
+3  A: 

I've not tried this, but it thnk the following should work:

ICriteria crit = session.CreateCriteria(typeof(theType))
                   .Add(Restrictions.IsNotNull("Message"))
                   .Add(Restrictions.IsNotEmpty("Message"));
o.k.w
Tried it out. It works. I guess its obvious, but the .Add() needs to be called on the ICriteria object as shown in taylonr's answer.
Amith George
Oh yes, I blindly copied the original one. Haha. Ok fixed it.
o.k.w
+1  A: 

Finally, I discovered the combination I was looking for!

lvCriteria.Add(Restrictions.Not(Expression.Eq("Msg", string.Empty)));

This combination of Restrictions and Expression works as expected; narrowing out all empty strings. I do not know why I could not achieve these results earlier even with:

lvCriteria.Add(Restrictions.Not(Restrictions.Eq("Msg", string.Empty)));

Thank you to all who tried.

alan
By the way, this response is from alan. The original poster.
alan
I believe that IsNotEmpty is for collections, but I think IsNotNull is for any object (at least IsNull can be used for any object).In that case, for the empty string, you could check the length of the string.
taylonr
Any suggestions as to how to check the length of the property?
alan
A: 

What you really need is:

ICriteria crit = session.CreateCriteria(typeof(theType))
.Add(Restrictions.Not(Restrictions.Eq("Msg", string.Empty)))
.Add(Restrictions.IsNotNull("Msg"))

This is working fine for me and profiler shows correct SQL i.e. something like:

msg<>'' and msg is not null. 

First answer did not work for me as Restrictions.IsNotEmpty/Empty applies only to collections (in NH 2.0.1 at least).

dyadenka