How to get the specific type of error returned by EntityFramework?

3

Following the question: How to intercept exceptions when working with the Entity Framework?

Is it possible to get some type of error identifier? For example, Primary Key Violation, Foreign Key Inconsistency, and in my specific case, when it is a single key violation.

Anyway, working with EntityFramework I'm intercepting the thrown exceptions as follows:

try {
    ...
}
catch (DbUpdateException e) {
    TempData["Mensagens"] = "Ocorreu um erro enquanto ...";
}

How to identify the specific EF error type and then be able to handle the message?

    
asked by anonymous 13.06.2014 / 03:52

1 answer

3

So:

try {
    ...
}
catch (DbUpdateException e) {
    switch (((SqlException)e.InnerException.InnerException).Number)
    {
             case 547:
                 {
                     //FK exception
                     TempData["Mensagens"] = "Chave Estrangeira";
                 }
             case 2627:
             case 2601:
                 {
                     //primary key exception
                     TempData["Mensagens"] = "Chave Primária";
                 }
             default:
                 {
                     TempData["Mensagens"] = "Erros";
                 }
    }
}

Here you put the message of your choice.

All errors contained in the MSDN Microsoft Developers - System Error Messages

Reference:

13.06.2014 / 04:13