Func<;t、 布尔>;vs手动表达式在C#lambda中的性能

Func<;t、 布尔>;vs手动表达式在C#lambda中的性能,c#,sql-server,lambda,C#,Sql Server,Lambda,请看以下几行: 1。在这种情况下,我直接在方法中键入where语句 public List<User> GetUsers() { return _entity.Where(x => x.Id == 1).ToList(); } 2。在本例中,我将Func用于泛型where子句 public List<User> GetUsers(Func<User, bool> where) { return _entity.Where(where).

请看以下几行:

1。在这种情况下,我直接在方法中键入where语句

public List<User> GetUsers()
{
    return _entity.Where(x => x.Id == 1).ToList();
}
2。在本例中,我将Func用于泛型where子句

public List<User> GetUsers(Func<User, bool> where)
{
    return _entity.Where(where).ToList();
}
var users = _acc.GetUsers(x => x.Id == 1);
如您所见,在案例2中,where子句缺少
其中1=[Extent1].[Id]
,因此整个记录都存储在内存中。您知道为什么在sql查询中where子句不被翻译吗?
我想在
.Where()
中使用
Func
,因此它是通用的,不需要为每个查询创建函数。
有没有办法使用
.Where(Func)
并在sql查询中查看已翻译的Where子句?

而不是

public List<User> GetUsers(Func<User, bool> where)
public List GetUsers(Func-where)
你应该使用

public List<User> GetUsers(Expression<Func<User, bool>> where)
public List GetUsers(表达式where)

当您使用
表达式时
实体框架能够正确地将其转换为SQL。另一方面,当您使用
Func
实体框架时,它不知道如何将其转换为SQL,因此使用内存处理。

如果希望lambda在SQL中执行,则需要将其作为表达式而不是函数传递:

public List<User> GetUsers(Expression<Func<User, bool>> where)
{
    return _entity.Where(where).ToList();
}
var users = _acc.GetUsers(x => x.Id == 1);
public List GetUsers(表达式where)
{
返回_entity.Where(Where.ToList();
}
var users=_acc.GetUsers(x=>x.Id==1);

如果您想知道区别是什么(毕竟lambda本身看起来是一样的),请看一看。

这是因为在这两种情况下,编译代码包含对两个不同扩展方法的调用:和
Queryable
类包含用于处理来自不同数据源(包括外部源)的数据的扩展方法,而
Enumerable
包含用于内存中对象处理的扩展方法<代码>可查询版本的
其中
接受
表达式
而不是
Func


Lamda表达式可以隐式转换为
expression
Func
,因此其他答案指出,您只需接受
expression
实例作为函数参数。

这么简单,我想知道为什么我的应用程序这么慢。。。谢谢
public List<User> GetUsers(Expression<Func<User, bool>> where)
public List<User> GetUsers(Expression<Func<User, bool>> where)
{
    return _entity.Where(where).ToList();
}
var users = _acc.GetUsers(x => x.Id == 1);