Reputation: 342
I am trying to create a method that links multiple updates to database using Entity Framework and Transaction Scope. I want to be able to do a Rollback in case of validation error/exception. My setup is like this:
using (TransactionScope scope = new TransactionScope())
{
try{
SomeBusinessLogic();
RepoMethod1();
Throw random Exception here;
RepoMethod2();
catch(Exception ex){
Transaction.Current.Rollback();
scope.Dispose();
return;
}
}
public RepoMethod1(){
using (MyContext context = new MyContext())
{
DoSomeWork();
context.SaveChanges();
}
}
Unfortunately, if exception gets thrown, Rollback doesn't happen. But it should, shouldn't it?!
Edit
So it seems my problem originated in me using CRM Dynamics through Entity Framework. This works when using with regular EF, but when using with CRM Dynamics it simply won't work. CRM Dynamics has it's own way of dealing with things.
Upvotes: 0
Views: 1638
Reputation: 668
The problem is that you don't commit your transaction and that you mix up a TransactionScope instance with the current ambient transaction. Further you don't have to rollback the failed transaction by hand, this will be done by the transaction manager in case the commit fails. Following code should do the job:
SomeBusinessLogic() // do this outside of the transaction because it's not part of it
try
{
using (TransactionScope scope = new TransactionScope())
{
RepoMethod1();
RepoMethod2();
scope.Complete(); // commits the transaction
} // end of using calls scope.Dispose()
}
catch (TransactionAbortedException ex)
{
// handle exception
}
Upvotes: 1