在我的 ASP.NET MVC 3 应用程序中,我使用 EF 4.2。在我的数据库中,我有一个列的唯一约束。
我尝试插入相同的数据以查看得到的结果,但出现以下错误:
更新条目时出错。有关详细信息,请参阅内部异常。
在内部异常中,我可以看到有关唯一约束的完整错误。但是我怎样才能唯一地捕捉到这个异常来告诉用户这个:
您再次输入相同的值。
这是我目前所做的:
try
{
UpdateModel<ConditionType>(conditionType, null, null, new string[] { "ConditionTypeId" });
_conditionTypeRepository.Save();
return RedirectToAction("conditiontype");
}
catch (Exception ex)
{
ModelState.AddModelError("", "There was an error while updating: " + ex.Message);
}
但这是一种通用方法。我想做的是提供一个特定的信息。
有什么想法吗?
编辑:
我厌倦了下面的但这次它没有抓住它:
catch (SqlException ex)
{
if (ex.Number == 2627)
{
ModelState.AddModelError("", "You are entering the same value again.");
}
ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
}
我挖了一点,结果发现它抛出了一个System.Data.Entity.Infrastructure.DbUpdateException
不包含异常号的异常类型。
编辑:
这是我如何解决问题的方法,但我确信这不是解决问题的最佳方法。知道如何重构这段代码吗?
catch (Exception ex) {
if (ex.InnerException.InnerException.GetType() == typeof(SqlException)) {
if (((SqlException)ex.InnerException.InnerException).Number == 2627)
ModelState.AddModelError("", "You are entering the same value again.");
else
ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
} else {
ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
}
}