Using Flag in Entity Framework Where Suggestion

I have a class (built by EF from my database) that has a field that is a flag. The field is stored in the database as an int in a column named CategoryEnum. I have an enumeration that sets valid flag values:

[Flags]
public enum RuleCategories
{
    None = 0x0000,
    ApplicantBased = 0x0001,
    LocationBased = 0x0002,
    PolicyBased = 0x0004,
    PropertyBased = 0x0008
}

When I try to restore objects using LINQ to Entities

var allRules = from r in context.Rules
               where  ((r.CategoryEnum & (int)categories) != 0)
               select r;

I get this error:

It is not possible to create a constant value of type 'Closure type'. In this context, only primitive types (such as Int32, String, and Guid) are supported.

or, if I try to pass an entity value to enum

var allRules = from r in context.Rules
               where (((RuleCategories)r.CategoryEnum & categories) != 0)
               select r;

I get another error:

Cannot enter type 'System.Int32' to enter RuleCategories'. LINQ to Entities only supports listing of Entity Data Model primitive data types.

How to select entities based on a flag?

+3
1

, EF 3.5. EF 4.0 VS2010. 3.5, . categories int , int :

int preCastCategories = (int)categories;
var allRules = from r in context.Rules
               where  ((r.CategoryEnum & preCastCategories) != 0)
               select r;
+5

Source: https://habr.com/ru/post/1753941/


All Articles