LINQ to SQL - 过滤了WHERE子句

时间:2015-02-03 17:07:36

标签: linq linq-to-sql

为什么where条件未在以下代码中应用?当我搜索时,结果不会被过滤。当我调试时,searchString确实有一个值,执行正在通过_data.Where子句,但它没有返回过滤结果。

我在这里做错了什么?

IQueryable<UserViewModel> _data = (
    from a in context.aspnet_Users
    join b in context.aspnet_Membership on a.UserId equals b.UserId
    where b.IsApproved == true
    select new UserViewModel
    {                                 
        UserId = a.UserId,
        UserName = a.UserName,
        FirstName = a.FirstName,
        LastName = a.LastName,
        EmailAddress = b.Email                                 
    })
    .OrderBy(a => a.FirstName)
    .ThenBy(b => b.LastName);

if (!String.IsNullOrEmpty(searchString))
{                  
   _data = _data
        .Where(x => x.FirstName.Contains(searchString))
        .Where(y => y.UserName.Contains(searchString))
        .Where(y => y.LastName.Contains(searchString))
        .Where(y => y.EmailAddress.Contains(searchString));
}

2 个答案:

答案 0 :(得分:1)

编写第二个查询的方式检查所有过滤字段以搜索字符串开头的记录,即对于FirstName LastName UserName 电子邮件都以相同的字符串开头。

我认为你想要的是一个查询,检查这些字段是否以搜索字符串开头,例如:

_data = _data.Where(x => x.FirstName.Contains(searchString) ||
                         x.UserName.Contains(searchString)  ||
                         x.LastName.Contains(searchString)  ||
                         x.EmailAddress.Contains(searchString));

答案 1 :(得分:0)

我怀疑这比你期望的更多“过滤”:

_data = _data.Where(x => x.FirstName.Contains(searchString))
             .Where(y => y.UserName.Contains(searchString))
             .Where(y => y.LastName.Contains(searchString))
             .Where(y => y.EmailAddress.Contains(searchString));

这要求这些字段的所有四个中都存在searchString。因此,如果您搜索“David”,那么它将无法找到我的记录,因为我的LastName不包含该字符串。

也许您想使用逻辑而不是逻辑?像这样:

_data = _data.Where(x => x.FirstName.Contains(searchString) ||
                         x.UserName.Contains(searchString) ||
                         x.LastName.Contains(searchString) ||
                         x.EmailAddress.Contains(searchString));