我有一个[标志]枚举是这样的:
I have a [Flags] enum like this:
[Flags]
public enum Status
{
None = 0,
Active = 1,
Inactive = 2,
Unknown = 4
}
一个状态枚举可以包含两个值,例如:
A Status enum may contain two values such as:
Status s = Status.Active | Status.Unknown;
现在我需要创建一个LINQ查询(LINQ到ADO.NET实体),并要求记录的状态为s以上,即主动或未知;
Now I need to create a linq query (LINQ to ADO.NET Entities) and ask for records whose status is s above, that is Active or Unknown;
var result = from r in db.Records
select r
where (r.Status & (byte)s) == r.Status
当然,我得到一个错误,因为LINQ到实体只知道处理原始类型的where子句。
Of course I get an error, because LINQ to Entities only knows to handle primitive types in the Where clause.
该错误是:
无法创建的恒定值 键入闭合型。只有原始 类型('如的Int32,String和 GUID')的在这方面的支持。
Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
有没有一种可行的方法?我可能有10个可能的值的状态枚举和查询5的状态中。如何使用标志枚举在一个优雅的方式,我构造查询?
Is there a workable way? I may have a status Enum with 10 possible values and to query for 5 of the statuses. How do I construct the query using Flags enum in an elegant way?
感谢。
更新
这似乎是一个LINQ到实体问题。我想在LINQ到SQL它的工作原理(不知道,也没有测试过)。
This seems to be a Linq to Entities problem. I think in LINQ to SQL it works (not sure, didn't tested).
只需使用 HasFlag()
var result = from r in db.Records
where r.Status.HasFlag(s)
select r