Come rollback di una transazione in Entity Framework
-
21-08-2019 - |
Domanda
string[] usersToAdd = new string[] { "asd", "asdert", "gasdff6" };
using (Entities context = new Entities())
{
foreach (string user in usersToAdd)
{
context.AddToUsers(new User { Name = user });
}
try
{
context.SaveChanges(); //Exception thrown: user 'gasdff6' already exist.
}
catch (Exception e)
{
//Roll back all changes including the two previous users.
}
O forse questo viene fatto automaticamente, il che significa che se si verifica un errore, le modifiche vengono annullate impegnano per tutti i cambiamenti. è vero?
Soluzione
OK
Ho creato un campione di un'applicazione come l'esempio dalla domanda e afterwords Ho controllato nel DB e non sono stati aggiunti gli utenti.
Conclusione: ObjectContext.SaveChange è automaticamente una transazione
.Nota. Credo che saranno necessari transazioni se l'esecuzione sprocs etc
Altri suggerimenti
Credo (ma non sono un esperto lungo tempo in EF), che fino a quando la chiamata a context.SaveChanges passa attraverso, la transazione non è stato avviato. Mi aspetto un'eccezione da questa chiamata sarebbe far ritirare automaticamente qualsiasi transazione è iniziato. Alternative (nel caso si voglia avere il controllo della transazione) [da "Programmazione Entity Framework" del J.Lerman O'Reilly, pag. 618]
using (var transaction = new System.Transactions.TransactionScope())
{
try
{
context.SaveChanges();
transaction.Complete();
context.AcceptAllChanges();
}
catch(OptimisticConcurrencyException e)
{
//Handle the exception
context.SaveChanges();
}
}
o
bool saved = false;
using (var transaction = new System.Transactions.TransactionScope())
{
try
{
context.SaveChanges();
saved = true;
}
catch(OptimisticConcurrencyException e)
{
//Handle the exception
context.SaveChanges();
}
finally
{
if(saved)
{
transaction.Complete();
context.AcceptAllChanges();
}
}
}