Linq 查询中的有线代理运算符
本文关键字:代理 运算符 查询 Linq | 更新日期: 2023-09-27 18:32:56
这是我的查询:
db.Users.Where(u =>
( u.Mobile.Contains(SearchStr)
|| u.FirstName.ToLower().Contains(SearchStr.ToLower())
|| u.LastName.ToLower().Contains(SearchStr.ToLower())
|| (u.Email.Contains(SearchStr)
)
&& (u.Type == SearchType || SearchType == 0)
&& (Confirmed == null || Confirmed == u.IsVerified)
&& (Banned == null || Banned == u.IsDeleted)
)
这列出了所有忽略Confirmed
、Banned
和SearchType
的用户。 无论这些值是null
、true
还是false
,结果都是相同的
我认为问题出在这里的左括号
(u.Email.Contains(SearchStr)
这基本上使条件像A OR B OR C AND D AND E AND F
.我不知道(我什至不想知道)这种逻辑表达式是如何评估的,而且很可能结果不是你所期望的。
试试这个
var query = db.Users.Where(u =>
(u.Mobile.Contains(SearchStr)
|| u.FirstName.ToLower().Contains(SearchStr.ToLower())
|| u.LastName.ToLower().Contains(SearchStr.ToLower())
|| u.Email.Contains(SearchStr)
)
&& (u.Type == SearchType || SearchType == 0)
&& (Confirmed == null || Confirmed == u.IsVerified)
&& (Banned == null || Banned == u.IsDeleted)
);
If SearchType == 0 or Confirmed == null or Banned == null
在任何时候,它都会返回所有内容。情况很可能是这样
删除这些条件,你应该很好
这更多的是评论然后回答,但想显示可能有助于 OP 调试的代码
db.Users.Where(u =>ISPassed(u));
private bool IsPassed(User u)
{
// put a debugger here
return ( u.Mobile.Contains(SearchStr)
|| u.FirstName.ToLower().Contains(SearchStr.ToLower())
|| u.LastName.ToLower().Contains(SearchStr.ToLower())
|| (u.Email.Contains(SearchStr)
)
&& (u.Type == SearchType || SearchType == 0)
&& (Confirmed == null || Confirmed == u.IsVerified)
&& (Banned == null || Banned == u.IsDeleted));
}
我按照Ivan Stoev所说查看了生成的sql。添加另一对括号解决了问题,但我仍然不明白逻辑,为什么以前不起作用,为什么现在有效
db.Users.Where(
u =>
(( u.Mobile.Contains(SearchStr) //added the parantheses in here
|| u.FirstName.ToLower().Contains(SearchStr.ToLower())
|| u.LastName.ToLower().Contains(SearchStr.ToLower())
|| (u.Email.Contains(SearchStr)
)) //and here
&& (u.Type == SearchType || SearchType == 0)
&& (Confirmed == null || Confirmed == u.IsVerified)
&& (Banned == null || Banned == u.IsDeleted)
))