Torna al Blog

    Entity Framework, Commit/RollBack and Transactions

    12 settembre 2014

    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. context1.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Save changes but maintain context2 current state. context2.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Commit succeeded since we got here, then completes the transaction. scope.Complete();

    // Now it is safe to update context state. context1.AcceptAllChanges(); context2.AcceptAllChanges(); }

    (original article : http://www.luisrocha.net/) Happy Coding !