James
James

Reputation: 77

How to catch DbUpdateException Unique exception?

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

Upvotes: 5

Views: 3761

Answers (1)

Henry
Henry

Reputation: 496

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

Upvotes: 7

Related Questions