1

在我的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); 
    } 
} 
+1

在調試窗口中單擊加號,您將看到發生的內部異常。 – 2011-12-27 13:38:03

+1

已經討論過類似的東西。看看這可以幫助你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

+0

@LasseEdsvik好的,我會告訴最終用戶這樣做。你仔細閱讀過這個問題嗎? – tugberk 2011-12-27 13:41:45

回答

3

你可以做這樣的事情尋找一個內部異常是SQLEXCEPTION,然後處理SQL異常不同。

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 
    } 
} 
+0

看起來很酷。現在給它一個嘗試。 – tugberk 2011-12-27 14:24:54

+0

這不會執行,因爲代碼不下降到InnerExceptions。 – Designpattern 2013-08-01 09:21:35

+0

@Designpattern - 良好的捕捉。我的意圖是走它(因此ex.Inner!= null),只是忘了實際更新變量。 – pstrjds 2013-08-01 14:15:57

0

爲了獲得最裏面的異常,你可以做這樣的事情:

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 
} 
0

人們還可以使用GetBaseException()方法,因爲這將讓你根本原因除外,它是把SQLException。

相關問題