BLOG LIST

Entity Framework, Commit/RollBack e Transazioni

Merita un appunto questo pezzo di codice, che serve a gestire transazioni annidate.

Vi capita di vedere questi messaggi ?

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

 

Questo succede sempre all’interno di cicli (for, while, etc.)

Allora probabilmente dovete spezzare la logica dei vostri loop di aggiornamento dati
(spesso e’ sufficiente portare il comando SaveChanges() fuori dal ciclo di loop)

oppure usare le transazioni :

 

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

(articolo originale : http://www.luisrocha.net/)

Happy Coding !

Blog List
An unhandled exception has occurred. See browser dev tools for details. Reload 🗙