2015-12-04 19 views
2

我寧願不做字符串比較,它看起來像我的可執行編號在InnerExeption編號字段中,但如果我試圖直接訪問它,就會出現編譯錯誤。如何從Asp.net 5中的DbUpdateException中檢索異常編號

try { 
    db.SaveChanges(); 
} catch (Microsoft.Data.Entity.DbUpdateException ex) { 
    // ex.InternalException.Number won't compile but appears to be there 

    // ex.InternalException.Message does compile but I think it seems less clean than a const comparison 
} 

一旦我得到的數字是有一個const我可以比較它?我試圖檢查重複的關鍵錯誤。

謝謝

+1

我不[查看](https://github.com/aspnet/EntityFramework/blob/dev/src/EntityFramework.Core/DbUpdateException.cs)一DbUpdateException.Number –

+0

看看的'Colin'和'ah'在這篇文章中的答案:http://stackoverflow.com/questions/22490842/finding-the-reason-for-dbupdateexception - 我認爲他們的方法來捕捉異常並給他們提供反饋,應該提供你正在尋找的細節。 –

回答

2

我找到了一個辦法。

db.User.Add(user); 
try { 
    db.SaveChanges(); 
} catch (Microsoft.Data.Entity.DbUpdateException ex) { 
    if (((System.Data.SqlClient.SqlException)ex.InnerException).Number == 2627) { 
     return new HttpStatusCodeResult(409); 
    } 
} 
+0

考慮將自己的答案標記爲已接受。 –

+1

謝謝,我有一個2天的等待期然後忘了 – matthewdaniel

相關問題