Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use flags enums in Linq to Entities queries?

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).

like image 417
Vasile Tomoiaga Avatar asked Dec 10 '22 19:12

Vasile Tomoiaga


2 Answers

Just use HasFlag()

var result = from r in db.Records
         where r.Status.HasFlag(s)
         select r
like image 89
Eat at Joes Avatar answered Jan 09 '23 04:01

Eat at Joes


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
like image 23
Gökhan CANGÜL Avatar answered Jan 09 '23 03:01

Gökhan CANGÜL