gpt4 book ai didi

asp.net-mvc - 当 "Delete"遇到 DB 约束时显示 DB 错误消息的最佳方式

转载 作者:行者123 更新时间:2023-12-04 18:22:37 25 4
gpt4 key购买 nike

我正在学习 MVC3 和 EF4.1 。我目前正在尝试使用新的 TT4 生成器使用 Database first EF 来生成精益数据类。我已经生成了一个 CRUD Controller ,并且遇到了如何最好地在 View 中显示数据库约束消息的问题。

我的代码到目前为止:

    [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();
}
}

非常感谢任何帮助。

埃德

最佳答案

最简单的事情之一是在异常消息中添加模型错误。这实质上将违反约束视为验证错误。但是,您可能应该为用户自定义消息。

[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);
}
}

关于asp.net-mvc - 当 "Delete"遇到 DB 约束时显示 DB 错误消息的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10352731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com