Duplicate Key Exception

Entity Framework throws exceptions from the DbContext’s SaveChanges method if there is a constraint violation in the database. If you have a property marked as invariant w.r.t. concurrency, that too will raise an exception at this point (a

DbUpdateConcurrencyException

Exception.

If you are using Sql Server, nested inside the UpdateException as an inner exception, which is nested in the DbUpdateException as an inner exception is a SqlException.

If you cast this to a

System.Data.SqlClient.SqlException

it will have a property Number that will correspond to the Sql Server Error Number

A common one to be interested in is the exceptions thrown by duplicate keys. In Sql Server there are two posssible error numbers : 2627 and 2601. Which one you get depends on the way the unique constraint was created.

An index created on a table created with the unique clause would result in a 2601. Adding a unique constraint will result in a 2627 in case of a duplicate key insertion.

                
catch (DbUpdateConcurrencyException ex)
{
    new ConcurrencyException();
}
catch (DbUpdateException ex)
{
    if( null == ex.InnerException || ex.InnerException.InnerException) throw;

    var innerException = ex.InnerException.InnerException 
                           as System.Data.SqlClient.SqlException;
    if (innerException != null && 
           (
               innerException.Number == 2627 || 
               innerException.Number == 2601)
           )  
      {
          throw new AlreadyInsertedException();
      }
      else
      {
          throw;
      }
}
This entry was posted in EF and tagged , , , . Bookmark the permalink.

Leave a Reply