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).
Just use HasFlag()
var result = from r in db.Records
where r.Status.HasFlag(s)
select r
In DB Flags enum must be integer. After that you can try it like this:
Status s = Status.Active | Status.Unknown;
var result = from r in db.Records
where (s & r.Status) == r.Status
select r
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With