2

在我的 winform 应用程序中,我使用以下代码来查找用户:

   var findUser =
                userService.Find(
                    u => u.UserName == UserNameTextBox.Text.Trim() && u.Password == PasswordTextBox.Text.Trim() && u.IsActive);

并在我的服务层中找到作为通用方法实现的方法:

public virtual TEntity Find(Func<TEntity, bool> predicate)
{
    return _tEntities.Where(predicate).FirstOrDefault();
}

当我执行此操作时,会生成以下 sql 代码并将其发送到 sql server:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName], 
[Extent1].[UserName] AS [UserName], 
[Extent1].[Password] AS [Password], 
[Extent1].[IsAdmin] AS [IsAdmin], 
[Extent1].[IsActive] AS [IsActive], 
[Extent1].[RowVersion] AS [RowVersion]
FROM [dbo].[Users] AS [Extent1]

有什么问题,我该如何修复主题?

4

1 回答 1

3

Where函数在多种类型上定义了多个重载作为扩展方法。

随着Func<TEntity, bool> predicate您调用Enumerable.Where它评估您在客户端的过滤,这就是它不生成正确查询的原因。

你需要的是Queryable.Where接受一个Expression<Func<TSource, bool>> predicate

因此,将您Find的方法签名更改为:

public virtual TEntity Find(Expression<Func<TEntity, bool>> predicate)
{
    return _tEntities.Where(predicate).FirstOrDefault();
}
于 2013-02-17T16:45:38.873 回答