2

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!

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

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.
Oh yes, I blindly copied the original one. Haha. Ok fixed it.
isn't IsNotEmpty meant only for collections?
1

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.

3 Comments

By the way, this response is from alan. The original poster.
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.
Any suggestions as to how to check the length of the property?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.