0
votes

I using Entity Framework 6. After calling SaveChanges method twice in my code, after DeleteObject, a ConcurrencyException occurred:

entities.DeleteObject(pu);

// First time           
entities.Context.SaveChanges(SaveOptions.None);

// everything is ok

// Second Time     
entities.Context.SaveChanges(SaveOptions.None);

// Concurrency exception

But with using AddObject this exception did not occur !

Exception message is:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Handling optimistic concurrency exceptions.

How I can control multiple SaveChanges calls before AcceptAllChanges without a concurrency exception?

2

2 Answers

2
votes

Are you calling the AcceptAllChanges() method before the second save? My understanding is that if you use SaveOptions.None, the context keeps the changes so they can be resubmitted to the database. If the first SaveChanges() succeeds, than the rowversion is updated in the db, but in the context, everything is kept as it was, so the second time it causes the conflict on the rowversion.

0
votes

You can use transaction

var yourContext = ((IObjectContextAdapter)db).ObjectContext;

try {
    yourContext.Connection.Open();
    using (var transaction = new TransactionScope()) {
        
        //you can implement entities.DeleteObject(pu) here

        db.SaveChanges();

        // Do something else

        db.SaveChanges();

        transaction.Complete();
    }
} finally {
    yourContext.Connection.Close();
}