Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a enum with flag in an Entity Framework query

i have a enum type like below

  [Flags]
    public enum WeekDays
    {

        Monday = 1,
        Tuesday = 2,
        Wednesday = 4,
        Thursday = 8,
        Friday = 16,
        Saturday = 32,
        Sunday = 64,
    }


   WeekDays dw = WeekDays.Friday | WeekDays.Monday | WeekDays.Saturday;

   int dwInt = (int)dw;

   var list = query.Where(f => f.FromDateTime.DayOfWeek == dwInt "??????????? what can i do there????").ToList();
like image 898
tobias Avatar asked Apr 25 '12 19:04

tobias


People also ask

How do I add a flag to an enum?

The "|=" operator actually adds a flag to the enum, so the enum now contains two flag bits. You can use "|=" to add bits, while & will test bits without setting them. And Bitwise AND returns a value with 1 in the targeted bit if both values contain the bit.

What is Flag in enum?

Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

What is enum in Entity Framework?

In Entity Framework, this feature will allow you to define a property on a domain class that is an enum type and map it to a database column of an integer type. Entity Framework will then convert the database value to and from the relevant enum as it queries and saves data.


1 Answers

Starting from Entity Framework 6.1, you can use the HasFlag extension method in your requests.

For example:

query.Where(f => f.FromDateTime.DayOfWeek.HasFlag(WeekDays.Friday | WeekDays.Monday)).ToList();

See https://entityframework.codeplex.com/workitem/1497 for details about the feature request and implementation.

like image 173
youen Avatar answered Oct 13 '22 09:10

youen