Reputation: 1706
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;
}
}
Upvotes: 2
Views: 9135
Reputation: 364259
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.
Upvotes: 4
Reputation: 152
Just cast to begin with:
public List<MyClass> FindAllOfEnum(MyEnum myEnum)
{
using (DbContext db = new DbContext())
{
return db.MyClasses.Where(x => x.MyEnum == (int)myEnum);
}
}
Upvotes: 2