Passing a comparison function as a parameter into

2019-08-09 19:47发布

I have a couple of Entity Framework functions that only differ in operators, e.g.

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

and so on. Obviously, this is a dumbed down version of my real program...

I guess it must be possible to somehow pass the operator as a parameter / lambda expression (since they're sort of canonical), but whatever I've tried so far along those lines results in the infamous "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities." error.

Any hints as to how to pass a comparison function as a parameter so that it can be translated into SQL? The query needs to run at the database level, I can't load the entities into memory and then run a lambda there...

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-09 20:19
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);
查看更多
登录 后发表回答