Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.HasFlag in LINQ to Entities?

I have a flag e.g.

[Flags]
public enum DaysOfTheWeek
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32,
    Sunday = 64
}

If I want to use Linq to filter based on a variable containing particular flags, I can try to useEnum.HasFlag in a lambda statement to filter for more than one flag e.g.

DaysOfWeek weekendFilter = DaysOfTheWeek.Saturday | DaysOfTheWeek.Sunday;
var weekends = allDays.Where(d => d.DayOfWeek.HasFlag(weekendFilter));

This currently gives:

LINQ to Entities does not recognize the method 'Boolean HasFlag(System.Enum)' method, and this method cannot be translated into a store expression.

like image 900
StuperUser Avatar asked Sep 06 '12 19:09

StuperUser


2 Answers

Enum flags are based on binary operations.

HasFlag = (allDays & (DaysOfTheWeek.Saturday | DaysOfTheWeek.Sunday)) != 0;

You can abstract that into an extension method if you wish.

To answer your question concretely:

DaysOfWeek weekendFilter = DaysOfTheWeek.Saturday | DaysOfTheWeek.Sunday;
var weekends = allDays.Where(d => (d.DayOfWeek & weekendFilter) != 0);

I know that you can use this predicate with LINQ to SQL. It will be translated to SQL (SQL Server supports binary arithmetic just fine). Not sure if EF is equally capable as its LINQ supports is generally far inferior to L2S.

like image 97
usr Avatar answered Nov 18 '22 17:11

usr


Looks like it has been fixed in EF 6.1.

Regarding EF Core however, check this.

like image 5
Shimmy Weitzhandler Avatar answered Nov 18 '22 19:11

Shimmy Weitzhandler