entity framework - Linq to Entities return All Rows



在我的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]

问题出在哪里?如何修复主题?

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

使用Func<TEntity, bool> predicate,您调用的是Enumerable.Where,它在客户端评估您的筛选,这就是为什么它不能生成正确的查询。

您需要的是接受Expression<Func<TSource, bool>> predicateQueryable.Where方法

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

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

最新更新