You can catch an UpdateException and handle the response.
First, the following code displays the errors that interest us in SQL:
SELECT error, description FROM master..sysmessages WHERE msglangid == 1033 AND description LIKE '%insert%duplicate%key%' ORDER BY error
The following output is displayed here:
2601 Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls. 2627 Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'. The duplicate key value is %ls.
So, from this we see that we need to catch the values ββof SqlException 2601 and 2627 .
try { using(var db = new DatabaseContext()){ //save db.SaveChanges(); //Boom, error } } catch(UpdateException ex) { var sqlException = ex.InnerException as SqlException; if(sqlException != null && sqlException.Errors.OfType<SqlError>() .Any(se => se.Number == 2601 || se.Number == 2627)) /* PK or UKC violation */ { // it a dupe... do something about it, //depending on business rules, maybe discard new insert and attach to existing item } else { // it some other error, throw back exception throw; } }
source share