private static bool HandleDbUpdateException(DbUpdateException ex, ModelStateDictionary modelState, Issue issue) { var baseEx = ex.GetBaseException(); if (baseEx is OptimisticConcurrencyException) { // Concurrency violation modelState.AddModelError("OptimisticConcurrencyError", "The issue was changed while you were editing it. Check the \"Force save changes\" box to override the latest values."); return true; } var sqlEx = baseEx as SqlException; if (sqlEx != null && sqlEx.Number == 2601 && sqlEx.Message.Contains("IDX_Issues_Title")) { // Unique index violation modelState.AddModelError("Title", String.Format("An issue with the title \"{0}\" already exists", issue.Title)); return true; } return false; }
// <asp:FormView ID="issueView" InsertMethod="InsertIssue" /> public void InsertIssue([CurrentUser]string currentUser) { if (String.IsNullOrEmpty(currentUser)) { ModelState.AddModelError("", "You must be signed in to create new issues"); return; } var issue = new Issue { CreatedBy = currentUser }; TryUpdateModel(issue); if (ModelState.IsValid) { _db.Issues.Add(issue); SaveChanges(issue); } }
private void SaveChanges(Issue issue) { try { _db.SaveChanges(); Response.Redirect("~/"); } catch (DbUpdateException ex) { if (!HandleDbUpdateException(ex, ModelState, issue)) { throw ex; } } }