3

I'm inserting a Tag when it already exists into the Tag table, hence it returns the message,

Message "Cannot insert duplicate key row in object 'dbo.Tag' with unique index 'IX_Tag_Name'. The duplicate key value is (Lemon).\r\nThe statement has been terminated." string

I've tried to catch this Unique exception by checking for the Number 2601 but am unable to access the Number property.

The Exception

Apparently this is how you are suppose to catch the exception but ex.InnerException.InnerException is null, so the switch statement never executes. How can I catch UniqueKey Violation exceptions with EF6 and SQL Server?

catch (DbUpdateException ex)
{
    if (ex.InnerException.InnerException is SqlException sqlException)
    {
        switch (sqlException.Number)
        {
            // If the tag already exists
            case 2601: // Unique Key violation
        }
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
James
  • 57
  • 2
  • 7
  • how about you just dont try to insert the duplicate tag? Apart from that the exception screenshot shows that its the first ```.InnerException``` however in your code you try to get the inner exception of your inner exception :-D – Tomek Jan 13 '21 at 04:45
  • Are you intentionally looking "two layers in" for `ex.InnerException.InnerException` or had you meant `ex.InnerException`? – George Kerwood Jan 13 '21 at 04:47

1 Answers1

6

Your code is checking the inner exception of your inner exception. This is null, and hence your code is failing. Instead do:

         catch (DbUpdateException ex)
        {
            if (ex.InnerException is SqlException sqlException)
            {
                switch (sqlException.Number)
                {
                    // If the tag already exists
                    case 2601: // Unique Key violation
                }
            }
        }
Henry
  • 486
  • 1
  • 5
  • 16