StuperUser StuperUser - 2 months ago 13
C# Question

Why doesn't HasFlag() work 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.

usr usr
Answer

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.