entity framework4.2:获取正确的数据库错误

在我的ASP.NET MVC 3应用程序中,我使用EF 4.2。 在我的数据库中,我对列有一个唯一的约束。

我尝试插入相同的数据,以便看到我得到的但我收到以下错误:

更新条目时发生错误。 有关详细信息,请参阅内部exception

在内部exception内部,我可以看到关于唯一约束的完整错误。 但是如何才能唯一地捕获此exception以告诉用户:

您再次输入相同的值。

这是我目前所做的事情:

try { UpdateModel(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); } 

我挖了一点,结果发现它抛出了一个exception类型的System.Data.Entity.Infrastructure.DbUpdateException ,它不包含exception编号。

编辑:

我在这里如何解决问题,但我相信这不是解决问题的最佳方法。 知道如何重构这段代码吗?

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

您可以执行类似这样的操作来查找SqlException的内部exception,然后以不同方式处理sqlexception。

 catch(Exception ex) { Exception current = ex; SqlException se = null; do { se = current.InnerException as SqlException; current = current.InnerException; } while (current != null && se == null); if (se != null) { // Do your SqlException processing here } else { // Do other exception processing here } } 

要获得最内层的Exception,您可以执行以下操作:

 SqlException se = null; Exception next = ex; while (next.InnerException != null) { se = next.InnerException as SqlException; next = next.InnerException; } if (se != null) { // Do your SqlException processing here } else { // Do other exception processing here } 

也可以使用GetBaseException()方法,因为这会导致根本原因exception,即SqlException。