wali ahmad wali ahmad - 1 month ago 14
ASP.NET (C#) Question

mvc 5 asp.net controller if function is passing error

here is I pass the correct user and password I will be able to get to new page but if it's wrong I get error:

this is the controller:

[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDbContext db = new OurDbContext())
{
var usr = db.userAccount.Single(u => u.Username == user.Username && u.Password == user.Password);
if(usr != null)
{
Session["UserID"] = usr.UserID.ToString();
Session["Username"] = usr.Username.ToString();
return RedirectToAction("LoggedIn");
}else
{
ModelState.AddModelError("", "Username or Password is wrong");
}
}
return View();
}


if I pass the wrong value I get error :

Line 49: using (OurDbContext db = new OurDbContext())
Line 50: {
Line 51: var usr = db.userAccount.Single(u => u.Username == user.Username && u.Password == user.Password);
Line 52: if(usr != null)
Line 53: {

Answer

Single returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists. So, consider to replace it with SingleOrDefault.

Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.