Linq未按预期执行

时间:2018-04-08 04:35:31

标签: c# sql-server asp.net-mvc linq

我有一个函数可以从数据库中的表命名用户中获取所有用户user_ingroup未包含在表[Authorize] public ActionResult DisplayUser(int? page, string groupId, string searchName, string searchPosition, string searchOffice) { try { if (null == db) { db = new vien_kiem_soat_streammingEntities(); } var UserIds = from p in db.user_ingroup.Where(p => p.group_id == groupId) select p.user_id; var users = db.users.Where(m => !UserIds.Contains(m.id)); if (!String.IsNullOrEmpty(searchName)) { ViewData["searchName"] = searchName; users = users.Where(us => us.full_name.ToLower().Contains(searchName.ToLower())); } if (!String.IsNullOrEmpty(searchPosition)) { users = users.Where(us => us.position.Contains(searchPosition)); ViewData["searchPosition"] = searchPosition; } if (!String.IsNullOrEmpty(searchOffice)) { users = users.Where(us => us.office.Contains(searchOffice)); ViewData["searchOffice"] = searchOffice; } ViewData["users"] = users.OrderBy(m => m.full_name).ToPagedList(page ?? 1, 2); var positions = from p in db.users.Where(p => !UserIds.Contains(p.id)) select p.position; List<string> pos = positions.Distinct().ToList(); ViewData["positions"] = pos; ViewData["group"] = groupId; return View("DisplayUser"); } catch (Exception ex) { return Redirect(Url.Action("Login", "Login", null)); } } 中,如下所示:

$(document).ready(function() {
    var scrollLink = $('.option-name');
    scrollLink.click(function(e){
        e.preventDefault();
        let linkRef = $(this).attr('href');
        let position = $(linkRef).offset().top;
    	$('html, body').animate({
    		scrollTop : position
    		}, 500)
    })
});

如果传递给此函数的所有参数都为null,但是如果其中一个参数具有值,则该函数将返回所有用户,无论用户是否已在组中,所以一切正常。

有人可以解释一下我怎么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

groupIdnull时,UserIds.Contains(m.id)将始终评估为false,这就是预期的目标。因此,看起来罪魁祸首是!运算符在下面的行..

var users = db.users.Where(m => !UserIds.Contains(m.id));