将比较函数作为参数传递到Entity Framework

时间:2014-11-12 17:46:27

标签: entity-framework lambda

我有几个实体框架功能只在运营商中有所不同,例如

public int GetCountEqual(int i)
{
  return Context.Entity.Where(e => e.Value == i).Count();
}

public int GetCountLess(int i)
{
  return Context.Entity.Where(e => e.Value < i).Count();
}

public int GetCountLessOrEqual(int i)
{
  return Context.Entity.Where(e => e.Value <= i).Count();
}

等等。显然,这是我真实节目的一个愚蠢版本......

我想一定有可能以某种方式将运算符作为参数/ lambda表达式传递(因为它们具有规范性),但是到目前为止,无论我在这些行中尝试过什么,都会导致臭名昭着 &#34; LINQ表达式节点类型&#39;调用&#39; LINQ to Entities不支持。&#34; 错误。

有关如何将比较函数作为参数传递以便将其转换为SQL的任何提示?查询需要在数据库级别运行,我无法将实体加载到内存中,然后在那里运行lambda ...

1 个答案:

答案 0 :(得分:3)

public int GetCount(Expression<Func<Entity, bool>> whereExpression)
{
   return Context.Entity.Where(whereExpression).Count();
}

int countEqual = GetCountEqual(e => e.Value == i);
int countLess = GetCountEqual(e => e.Value < i);
int countLessOrEqual = GetCountEqual(e => e.Value <= i);