Reputation: 449
I am learning MVC3 and EF4.1 . I am currently experimenting with Database first EF with the new the TT4 generator to generate lean data classes. I have generated a CRUD controller, and have come across the issue of how best to display DB constraint messages in the View.
My code is so far:
[HttpPost]
public ActionResult Delete(Guid id, aspnet_Users User)
{
string errorMessage = string.Empty;
try
{
// TODO: Add delete logic here
db.Entry(User).State = System.Data.EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
catch(Exception err)
{
return Content(err.InnerException.StackTrace);
//return View();
}
}
Any help greatly appreciated.
Ed
Upvotes: 2
Views: 2910
Reputation: 43077
One of the simplest things to do is add a model error with the exception message. This essentially treats the constraint violation as a validation error. You should probably customize the message for the user, however.
[HttpPost]
public ActionResult Delete(Guid id, aspnet_Users User)
{
try
{
// TODO: Add delete logic here
db.Entry(User).State = System.Data.EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
catch(Exception err)
{
ModelState.AddModelError(String.Empty, err.Message);
return View(User);
}
}
Upvotes: 4