Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle UpdateException - 'Violation of PRIMARY KEY constraint' on Entity Framework?

I have an appication that allows multiple users and a database table which has 2 IDs as a compound key. These IDs are also foreign keys from another table. So when 2 users try to add an entry to this tabel with the same IDs one of them gets an UpdateException because of Primary Key constaint violation. I already found out that it should be handled like this:

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

But what do I actually do on the "//Handle here" part. I tried refreshing the object but it is in the "Added" state and therefor can not be refreshed. What I whant it to do is: Acknowledge that there is already an object with these IDs, drop its object that it wanted to insert and load the existing object from the database. How can I do that?

like image 599
DerSeegler Avatar asked Apr 08 '14 16:04

DerSeegler


1 Answers

Since I got an upvote I looked back how I solved this. So here is what I did:

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

Edit:

Note that UpdateException has been renamed to DbUpdateException starting with EF 4.1.

like image 71
DerSeegler Avatar answered Oct 01 '22 19:10

DerSeegler