.net - 如何在 Linq to Entities 查询中使用标志枚举?

标签 .net linq enums flags

我有一个像这样的 [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/

相关文章:

c# - 单元测试插入/更新/删除

c# - 从哪里开始学习 LINQ 最好?

C# 枚举类型安全

c# - MongoDB 中枚举的自定义序列化

.net - App_LocalResources 如何与 MVC 配合使用?

.net - 无法创建迁移。错误 MSB1009 : Project file does not exist

c# - 如何将 Image 类型转换为 Image<Bgr, Byte>?

c# - LINQ错误: The null value cannot be assigned to a member with type System. Int32,它是非空值类型

c# - 翻译 "Multilanguage"枚举 javascript/c#

.net - 如何使用 SwashBuckle 将路径参数添加到 Controller ?