How to handle UpdateException - "PRIMARY KEY constraint violation" on Entity Framework?

I have an application that allows multiple users and a database table to have 2 identifiers as a composite key. These identifiers are also foreign keys from another table. Therefore, when 2 users try to add an entry to this column with the same identifiers, one of them gets an UpdateException due to a violation of the main key constant. I already found out that it should be processed as follows:

try
{
    result = base.SaveChanges(options);
}
catch (UpdateException ex)
{
    SqlException innerException = ex.InnerException as SqlException;
    if (innerException != null && innerException.Number == 2627 || innerException.Number == 2601)
    {
        // handle here
    }
    else
    {
        throw;
    }
}

"//Handle here". , "" . , : , , , . ?

+6
4

, , . , :

// Exception number 2627 = Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.
// Exception number 2601 = Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'.
// See http://msdn.microsoft.com/en-us/library/cc645603.aspx for more information and possible exception numbers
if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
{
    // Resolve the primary key conflict by refreshing and letting the store win
    // In order to be able to refresh the entity its state has to be changed from Added to Unchanged
    ObjectStateEntry ose = ex.StateEntries.Single();
    this.ObjectStateManager.ChangeObjectState(ose.Entity, EntityState.Unchanged);
    base.Refresh(RefreshMode.StoreWins, ose.Entity);

    // Refresh addedChanges now to remove the refreshed entry from it
    addedChanges = this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Where(s => !s.IsRelationship);
}
else
{
    throw;
}

:

, UpdateException DbUpdateException, EF 4.1.

+2

, - async, , async...

try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
    SqlException innerException = ex.InnerException.InnerException as SqlException;
    if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
    {
        //your handling stuff
    }
    else
    {
        throw;
    }
}

, DbUpdateException, catch ex.InnerException InnerException, , ...

+1

, 2 UpdateException - constaint .

- ( , ), .

, : , , , .

, , ..

  • , , "".
  • - - .
  • , . ? , ? , ( , , ). , , , , , .

:

var exisitingEntity = context.TheEntity;
existingEntity.Property1 = options.Property1;
existingEntity.Property2 = options.Property2;
...
context.SaveChanges(existingEntity);
return "Object already existed, but was updated with the values passed in."
0

, , , .

, , . , , , , :

if(base.object.Any(o=> o.Id == command.Id){
///Object exists, your "// handle here" goes here...
}else{
///No such object, save your changes normally
}

, ... , !

0

Source: https://habr.com/ru/post/1535591/


All Articles