5

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
        }
    }
}
2
  • 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 Commented Jan 13, 2021 at 4:45
  • Are you intentionally looking "two layers in" for ex.InnerException.InnerException or had you meant ex.InnerException? Commented Jan 13, 2021 at 4:47

1 Answer 1

7

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
                }
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.