C# 输入电子邮件和密码组合时LINQ扩展方法引发错误(System.InvalidoPerationException)

C# 输入电子邮件和密码组合时LINQ扩展方法引发错误(System.InvalidoPerationException),c#,asp.net,linq,C#,Asp.net,Linq,当我输入数据库中不存在的电子邮件和密码组合时,LINQ扩展方法引发错误 错误:System.InvalidOperationException{“序列不包含元素”} 这是我的密码 [HttpPost] public ActionResult Login(UserLogin userlogin) { ViewBag.LoginError = ""; if (ModelState.IsValid) {

当我输入数据库中不存在的电子邮件和密码组合时,LINQ扩展方法引发错误

错误:System.InvalidOperationException{“序列不包含元素”}

这是我的密码

[HttpPost]
    public ActionResult Login(UserLogin userlogin)
    {          

        ViewBag.LoginError = "";
        if (ModelState.IsValid)
        {
            //no validation errors
           //userContext.Users gives a list with all users on databse
           //here is my linq query to select the user with valid email and password combination

            User loggedInUser = (from user in userContext.Users
                                 where user.EmailId == userlogin.UserEmail & user.Password == userlogin.UserPassword
                                 select user).First();//Error Source

            if (loggedInUser != null)
            {
                ViewBag.ValidUser = loggedInUser;
                return RedirectToAction("UserHomePage", "UserHome");
            }
            else
            {
                ViewBag.LoginError = "Invalid User name and Password Combination";
                return View("Index");
            }
        }
        return View("Index");
    }

关于

您要先使用而不是
——如果找不到元素,将返回
null
。通常还应使用(而不是
&
),除非您有意要计算这两个表达式。

如果没有具有给定用户名密码组合的用户,则查询:

from user in userContext.Users
where user.EmailId == userlogin.UserEmail & user.Password == userlogin.UserPassword
select user
将不会产生任何对象,对其调用
First()
将引发该异常

您是否考虑过使用:如果没有对象,那么它将返回null(假设
user
是引用类型)