Linq查询中的有线动作运算符

时间:2016-02-03 09:40:03

标签: c# linq linq-to-entities

这是我的疑问:

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)
 )

此列表忽略了ConfirmedBannedSearchType的所有用户。结果是相同的,无论这些值是nulltrue还是false

4 个答案:

答案 0 :(得分:1)

我认为问题出在这里的空心括号

(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)
);

答案 1 :(得分:0)

If SearchType == 0 or Confirmed == null or Banned == null在任何时候,都会返回一切。可能就是这种情况

删除这些条件,你应该是好的

答案 2 :(得分:0)

这是更多的评论,然后回答,但希望显示可能有助于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));
    }

答案 3 :(得分:0)

我查看生成的sql,Ivan Stoev说。 添加另一对括号解决了这个问题,但我仍然没有得到逻辑,为什么之前没有工作,为什么现在正在工作

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)

                        ))