如何在NHibernate中查询存储为枚举的标志 [英] How to query flags stored as enum in NHibernate

查看:135
本文介绍了如何在NHibernate中查询存储为枚举的标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何执行HQL或Criteria搜索(后者是首选),涉及用作标志的枚举。换句话说,我有一个持久的枚举属性存储某种标志。我想查询所有设置了这些标志之一的记录。使用Eq将不起作用,因为这只会是真的,如果这是唯一的标志。



使用Criteria API解决这个问题将是最好的,但是

解决方案

以下是使用标准API的方法: p>

  [Flags] 
enum Bar {
A = 0x01,
B = 0x02,
C = 0x04
}

var criteria = this.Session.CreateCriteria< Foo>()
.Add(BitwiseFlags.IsSet(Bar,Bar.A | BarC));

使用:

 code> public class BitwiseFlags:LogicalExpression 
{
private BitwiseFlags(string propertyName,object value,string op):
base(new SimpleExpression(propertyName,value,op),
Expression.Sql(?,值,NHibernateUtil.Enum(value.GetType())))
{
}

保护重写字符串Op
{
get {return=;


$ b public static BitwiseFlags IsSet(string propertyName,Enum flags)
{
返回新的BitwiseFlags(propertyName,flags,&);
}
}

应该生成以下输出where子句:

  FROM _TABLE 
WHERE(this_Bar& 5 = 5)
/ pre>

它应该给你带有标志Bar.A和Bar.C集(不包括其他)的行。你应该可以使用它连接和分离。


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.

解决方案

Here's how you could do it with the criteria API:

[Flags]
enum Bar{
   A = 0x01,
   B = 0x02,
   C = 0x04
}

var criteria = this.Session.CreateCriteria<Foo>()
            .Add( BitwiseFlags.IsSet( "Bar", Bar.A | Bar.C ) );

using:

public class BitwiseFlags : LogicalExpression
{
    private BitwiseFlags( string propertyName, object value, string op ) :
        base( new SimpleExpression( propertyName, value, op ),
        Expression.Sql( "?", value, NHibernateUtil.Enum( value.GetType() ) ) )
    {
    }

    protected override string Op
    {
        get { return "="; }
    }

    public static BitwiseFlags IsSet(string propertyName, Enum flags)
    {
        return new BitwiseFlags( propertyName, flags, " & " );
    }
}

should generate the following output where clause:

 FROM _TABLE
 WHERE  (this_.Bar & 5 = 5)

which should give you rows that have flags Bar.A and Bar.C set (excluding everything else). You should be able to use it with conjunction and disjunction too.

这篇关于如何在NHibernate中查询存储为枚举的标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆