0

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

doesn't exist rowversion or timestamp column in table pu only exist datetime2 , money , int
0

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

1 Comment

TransactionScope is for revert , but my question is why every things is OK in first call but i get error for second call and don't have any code between savechanges

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.