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

Asked

Viewed 411 times

3

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

Is it possible to get any error type 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 am intercepting the exceptions released as follows:

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

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

1 answer

3


Thus:

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

There you put the message of your preference.

All errors contained in MSDN Microsoft Developers - System Error Messages

Reference:

  • Got it I’ll edit

  • 1

    http://msdn.microsoft.com/en-us/library/cc645603(v=sql.105). aspx take a look at this ...

  • 3

    Yes, as I understood yes the mistakes follow a pattern, this is good, because there depends on the bank

  • 3

    @Tremdoido, I will do a deeper research and talk to a group about Entity and its exceptions if I discovered something new warning you on (@)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.