2

I'd rather not do string comparison and it looks like my exeption number is in the InnerExeption number field but I get build errors if I try to access it directly.

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
}

Once I do get the number is there a const I can compare it with? I'm trying to check for duplicate key error.

Thanks

matthewdaniel
  • 1,842
  • 4
  • 21
  • 35
  • 1
    I don't [see](https://github.com/aspnet/EntityFramework/blob/dev/src/EntityFramework.Core/DbUpdateException.cs) a DbUpdateException.Number – Stafford Williams Dec 05 '15 at 00:22
  • Take a look at the answers from 'Colin' and 'a-h' on this post: http://stackoverflow.com/questions/22490842/finding-the-reason-for-dbupdateexception -- I think that their approaches to catching the Exceptions and giving feedback from them, should give the details you are looking for. – David Tansey Dec 05 '15 at 00:35

1 Answers1

2

I found a way to do it.

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);
    }
}
matthewdaniel
  • 1,842
  • 4
  • 21
  • 35