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;
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
Of course I get an error, because LINQ to Entities only knows to handle primitive types in the Where clause.
The error is:
Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
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?
Thanks.
Update
This seems to be a Linq to Entities problem. I think in LINQ to SQL it works (not sure, didn't tested).
Active
andUnknown
. Is that what you want? – IntermissionStatus.Active|Status.Unknown
" is equivalent to "1|4
" which is5
. So yourwhere
clause is effectively saying "where (r.Status & 5) == r.Status
", which is the same as "where r.Status == 5
", which is the same as saying (in English) "wherer.Status
is bothActive
andUnknown
"! – IntermissionHasFlag
is supported in LINQ-to-Entities. See: data.uservoice.com/forums/… and entityframework.codeplex.com/workitem/1497 – Plantation