传递一个比较函数作为参数到实体框架(Passing a comparison function as

2019-10-21 06:28发布

我有一对夫妇的实体框架的功能,只有在运营商不同,例如

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表达式(因为他们是那种典型),但无论我沿着臭名昭著“的LINQ表达式节点类型“调用这些线结果到目前为止已经试过“不支持LINQ到实体。” 错误。

任何提示如何传递一个比较函数作为参数,以便它可以被转换成SQL? 查询需要在数据库级别上运行,我不能在实体加载到内存中,然后运行拉姆达有...

Answer 1:

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


文章来源: Passing a comparison function as a parameter into Entity Framework