请看以下几行:

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

public List<User> GetUsers()
{
    return _entity.Where(x => x.Id == 1).ToList();
}

执行的SQL查询是:
SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Username] AS [Username],
    [Extent1].[Password] AS [Password],
    [Extent1].[Email] AS [Email],
    [Extent2].[Id] AS [Id1]
    FROM  [dbo].[Account_Users] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Account_Profiles] AS [Extent2] ON [Extent1].[Id] = [Extent2].[UserId]
    WHERE 1 = [Extent1].[Id]

2.在这种情况下,我将Func用作泛型where子句
public List<User> GetUsers(Func<User, bool> where)
{
    return _entity.Where(where).ToList();
}
var users = _acc.GetUsers(x => x.Id == 1);

执行的SQL查询是:
SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Username] AS [Username],
    [Extent1].[Password] AS [Password],
    [Extent1].[Email] AS [Email],
    [Extent2].[Id] AS [Id1]
    FROM  [dbo].[Account_Users] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Account_Profiles] AS [Extent2] ON [Extent1].[Id] = [Extent2].[UserId]

如您所见,在情况2中,缺少WHERE 1 = [Extent1].[Id]的where子句,因此整个记录都存储在内存中。你有什么主意,为什么在SQL查询中不翻译where子句?

我想在Func<t, bool>中使用.Where(),因此它是通用的,不需要为每个查询创建函数。
有什么方法可以使用.Where(Func<t, bool>),还可以在sql查询中查看转换后的where子句?

最佳答案

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

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

如果您想知道两者之间有什么不同(毕竟,lambda本身看起来一样),请查看this question

关于c# - Func <t,bool>与C#lambda中的手动表达性能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31368751/

10-10 18:12
查看更多