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())
{

context1.SaveChanges(SaveOptions.DetectChangesBeforeSave);


context2.SaveChanges(SaveOptions.DetectChangesBeforeSave);


scope.Complete();


context1.AcceptAllChanges();
context2.AcceptAllChanges();
}

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

Happy Coding !

Potrebbe interessanti anche…