在我的ASP.NET MVC 3應用程序中,我使用EF 4.2。在我的數據庫中,我對列有一個唯一的約束。實體框架4.2:獲取正確的數據庫錯誤
我嘗試以看看有什麼我可以插入相同的數據,但我得到下面的錯誤:
An error occurred while updating the entries. See the inner exception for details.
內部異常裏面,我可以看到的唯一約束完整的錯誤。但我怎麼能唯一捕獲這個異常告訴用戶這一點:
You are entering the same value again.
這是我目前做的:
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);
}
}
在調試窗口中單擊加號,您將看到發生的內部異常。 – 2011-12-27 13:38:03
已經討論過類似的東西。看看這可以幫助你http://stackoverflow.com/questions/3694359/entity-framework-how-to-properly-handle-exceptions-that-occur-due-to-sql-constr – Pavan 2011-12-27 13:40:37
@LasseEdsvik好的,我會告訴最終用戶這樣做。你仔細閱讀過這個問題嗎? – tugberk 2011-12-27 13:41:45