Where Clause with Enums in Entity Framework

entity-framework enums lambda linq

Question

So here is what I have for my enum. Really basic. The enum does NOT have a corresponding database table. Rather, whenever a class has a MyEnum property, the database has an int column. That all works fine.

public enum MyEnum : int
{
    Zero = 0,
    One = 1,
    Two = 2
}

This is my class, it has its own table in the database.

public class MyClass
{
    public long MyClassID { get; set; }
    public MyEnum { get; set; }
}

So when I go to pull out a MyClass object, the MyEnum property is set to its corresponding int value, hooray. My problem is when I try to write a query that uses the MyEnum property, I get an error.

public List<MyClass> FindAllOfEnum(MyEnum myEnum)
{
    using (DbContext db = new DbContext())
    {
        return db.MyClasses.Where(x => x.MyEnum == myEnum);
    }
}

// ERROR:
// The specified type member 'MyEnum' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

So I tried writing this Value extension method, but I realized that would only allow me to take out the MyEnum reference on the right-hand side of the comparison, since I can't put the function actually in the lambda expression. What do?

public static class Extensions
{
    public static int Value(this MyEnum myEnum)
    {
        return (int)myEnum;
    }
}
1
2
11/15/2011 10:54:46 PM

Popular Answer

This is not supported until next major version of EF (.NET 4.5). Until .NET 4.5 you must pass int to your queries (conversion must be done outside of your query). The best workaround is this.

4
11/16/2011 11:29:13 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow