views:

28

answers:

1

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 enum that specifies the permissible values of the flag:

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

When I try to retrieve the objects using LINQ to Entities

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

I get this error:

Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

or, if I try to cast the entity value to the enum

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

I get a different error:

Unable to cast the type 'System.Int32' to type RuleCategories'. LINQ to Entities only supports casting Entity Data Model primitive types.

How do I select entities based on a flag?

Thanks

A: 

I am going to guess and say that you are using the good old EF 3.5. This works without problems with EF 4.0 in VS2010. There is a problem with the 3.5 version, however, and you will have to use a workaround. Cast the categories variable to int before the query, and then use your int variable inside the query itself:

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