Entity Framework, Commit/RollBack and Transactions

This snippet of code works for nested transactions.

Do you often get these messages ?

“New transaction is not allowed because there are other threads running in the session.”

This usually happens when you have a “SaveChanges()” inside a loop.

Then probably you must break the logic of your data update loops
(example, take SaveChanges() out of the loop).

Or you can use transactions :


public TransactionScope CreateTransactionScope()
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOptions.Timeout = TimeSpan.MaxValue;

return new TransactionScope(TransactionScopeOption.Required, transactionOptions);

using (TransactionScope scope = new TransactionScope())
// Save changes but maintain context1 current state.

// Save changes but maintain context2 current state.

// Commit succeeded since we got here, then completes the transaction.

// Now it is safe to update context state.

(original article : http://www.luisrocha.net/)

Happy Coding !

Potrebbe interessanti anche…