I'm trying to write some dynamic linq expression for my EF app.
I have an enum that represents a type:
public class MyEntity {
public int? One { get; set; }
public int? Two { get; set; }
public int? Three { get; set; }
// other fields..
}
public enum MyType {
One,
Two,
Three
}
public static Expression<Func<MyEntity, int?>> GetItem(MyType myType) {
switch(myType) {
case One: return (e) => e.One;
case Two: return (e) => e.Two;
case Three: return (e) => e.Three;
default: throw new NotImplementedException();
}
}
Depending on the type, I want to perform queries against it. So for example, I want to see if my type column equals to a certain value:
public static Expression<Func<MyEntity, int?>> EqualsValue(MyType myType, int value) {
return Expression.Equal(GetItem(myType), Expression.Constant(value));
}
This is giving me a compiler error that it can't cast from BinaryExpression to Expression>. Is there a better way to do this?
UPDATE:
I would like to use it in the EF like: ctx.MyEntities.Where(EqualsValue(myType, value)).Where(u => u.UserID == userID)
so the return type has to be Expression<Func<MyEntity, int?>>
.. I need it to work for Linq to SQL as well as EF DataService.
You should be able to do:
public static Expression<Func<MyEntity, int?>> EqualsValue(MyType myType, int value) {
return (e) => GetItem(myType)(e) == value;
}