EF的动态linq表达式

时间:2012-10-01 21:54:59

标签: c# linq entity-framework dynamic-linq

我正在尝试为我的EF应用程序编写一些动态linq表达式。

我有一个表示类型的枚举:

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();
  }
}

根据类型,我想对它执行查询。因此,例如,我想看看我的类型列是否等于某个值:

public static Expression<Func<MyEntity, int?>> EqualsValue(MyType myType, int value) {
  return Expression.Equal(GetItem(myType), Expression.Constant(value));
}

这给了我一个编译器错误,它无法从BinaryExpression转换为Expression&gt;。有更好的方法吗?

更新:

我想在EF中使用它:ctx.MyEntities.Where(EqualsValue(myType, value)).Where(u => u.UserID == userID)所以返回类型必须是Expression<Func<MyEntity, int?>> ..我需要它来为Linq to SQL以及EF DataService工作。

1 个答案:

答案 0 :(得分:1)

你应该可以这样做:

public static Expression<Func<MyEntity, int?>> EqualsValue(MyType myType, int value) {
  return (e) => GetItem(myType)(e) == value;
}
相关问题