Linq to Entities返回All Rows

时间:2013-02-17 16:11:03

标签: entity-framework linq-to-entities code-first

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

问题是什么?如何修复主题?

1 个答案:

答案 0 :(得分: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();
}