我尝试在我的网络应用程序中进行自定义登录
这是型号:
public class Clients { public int ID { get; set; } [required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Display(Name = "Ф.И.О")] public string UserName { get; set; } [Display(Name = "Должность")] public string Position { get; set; } [required] [DataType(DataType.Password)] [Display(Name = "Пароль")] public string Password { get; set; } [Compare("Password",ErrorMessage = "Пароли не совпадают.")] [DataType(DataType.Password)] public string ConfirmPassword { get; set; } }
我像这样制作控制器:
public class ClientsLoginController : Controller { public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Clients user ) { using (OurDbContext db = new OurDbContext()) { var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password); if (usr != null) { Session["UserId"] = usr.ID.ToString(); Session["Email"] = usr.Email.ToString(); return RedirectToAction("Login"); } else { ModelState.AddModelError("","Email or Login not correct"); } return View(); } } }
这是视图:
<h2>Login</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Clients</h4> <hr /> @Html.ValidationSummary(true,"",new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Email,htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email,new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email,new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Password,htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Password,new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Password,new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ConfirmPassword,htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ConfirmPassword,new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ConfirmPassword,new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Login" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List","Index") </div>
`An exception of type ‘System.InvalidOperationException’ occurred in
System.Core.dll but was not handled in user codeAdditional information: Sequence contains no elements`
在这一行
var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password);
我该如何解决?
解决方法
When you get the LINQ Error “Sequence contains no elements”,this is
usually because you are using theFirst()
orSingle()
command
rather thanFirstOrDefault()
andSingleOrDefault()
.
有关详细信息link