如何执行涉及用作标志的枚举的 HQL 或标准搜索(后者是首选)。换句话说,我有一个存储某种标志的持久化枚举属性。我想查询所有设置了这些标志之一的记录。使用 Eq 当然不会起作用,因为只有当这是唯一的标志集时,它才会为真。
使用 Criteria API 解决这个问题是最好的,但如果这只能使用 HQL 来解决,那也很好。
最佳答案
以下是使用标准 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 子句:
FROM _TABLE
WHERE (this_.Bar & 5 = 5)
这应该为您提供设置了标志 Bar.A 和 Bar.C 的行(不包括其他所有内容)。您也应该能够将它与连词和析词一起使用。
关于c# - 如何查询在 NHibernate 中存储为枚举的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2805661/