views:

276

answers:

3

How to do either a HQL or a Criteria search (the latter is preferred) involving an enum that is used as flags. In other words, I have a persisted enum property that stores some kind of flags. I want to query all the records that have one of these flags set. Using Eq won't work of course because that will only be true, if that is the only flag set.

Solving this using the Criteria API would be the best, but if this is only doable using HQL that is good too.

A: 

You are looking for Expression.Or if you are querying 2 values or Expression.Disjunction if you are querying for more than 2 values:

criteria.Add(
  Expression.Disjunction()
    .Add(Expression.Eq("property", value1))
    .Add(Expression.Eq("property", value2))
    .Add(Expression.Eq("property", value3))
)
Jan Willem B
I don't think this will work with flag based enums
SztupY
i see. good example of the wrong answer then.
Jan Willem B
+3  A: 

HQL is easy:

var matching = session.CreateQuery(@"
                       from MyEntity
                       where FlagsProperty & :flag = :flag
                       ")
                      .SetParameter("flag", MyEnum.FlagValue)
                      .List<MyEntity>();
Diego Mijelshon
Is there a way of achieving the same using NHibernate LINQ ? I am trying to do something like this .... from obj in Session.Linq<MyEntity>() where ( obj.FlagsProperty ...where flag is the parameter but it is throwing exception "System.NullReferenceException : Object reference not set to an instance of an object"
nabeelfarid
Steve just answered this in the forum, deleting my previous reply
Diego Mijelshon
yes it is...thanks
nabeelfarid
+1  A: 

Here is how I solved using Criteria:

Expression.Eq(
  Projections.SqlProjection("({alias}." + propertyname + " & " + 
    ((int)value).ToString() + ") as " + propertyname + "Result",
    new[] { propertyname + "Result" },
    new IType[] { NHibernateUtil.Int32 }
  ), value );
SztupY