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

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

问题描述

如何进行涉及用作标志的枚举的 HQL 或标准搜索(后者是首选).换句话说,我有一个存储某种标志的持久化枚举属性.我想查询所有设置了这些标志之一的记录.当然,使用 Eq 是行不通的,因为只有在设置了唯一标志时,才会如此.

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.

使用 Criteria API 解决这个问题是最好的,但如果这只能使用 HQL 来解决,那也很好.

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

推荐答案

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

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

使用:

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, " & " );
    }
}

应生成以下输出 where 子句:

should generate the following output where clause:

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

应该为您提供设置了标志 Bar.A 和 Bar.C 的行(不包括其他所有内容).您也应该能够将它与连词和析取一起使用.

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天全站免登陆