为什么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));
}
答案 0 :(得分:1)
编写第二个查询的方式检查所有过滤字段以搜索字符串开头的记录,即对于FirstName 和 LastName 和的用户em> 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));