如何使用LINQ的标志枚举to Entities查询? [英] How to use flags enums in Linq to Entities queries?

查看:319
本文介绍了如何使用LINQ的标志枚举to Entities查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个[标志]枚举是这样的:

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

这篇关于如何使用LINQ的标志枚举to Entities查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆