我有一个像这样的 [Flags] 枚举:
[Flags]
public enum Status
{
None = 0,
Active = 1,
Inactive = 2,
Unknown = 4
}
Status 枚举可能包含两个值,例如:
Status s = Status.Active | Status.Unknown;
现在我需要创建一个 linq 查询(LINQ to ADO.NET Entities)并请求状态为 s 以上的记录,即事件或未知;
var result = from r in db.Records
select r
where (r.Status & (byte)s) == r.Status
当然我得到一个错误,因为 LINQ to Entities 只知道处理 Where 子句中的原始类型。
错误是:
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 个状态。如何以优雅的方式使用 Flags 枚举构造查询?
谢谢。
更新
这似乎是一个 Linq to Entities 问题。我认为在 LINQ to SQL 中它可以工作(不确定,未测试)。
最佳答案
只需使用 HasFlag()
var result = from r in db.Records
where r.Status.HasFlag(s)
select r
关于.net - 如何在 Linq to Entities 查询中使用标志枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1426577/