Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply transaction in Entity framework

I have two tables. I am updating those tables using entity framework. here is my code

public bool UpdateTables()
{
      UpdateTable1();
      UpdateTable2();
}

If any table update operation fails other should not be committed how do i achieve this in entity framework?

like image 815
Ulhas Tuscano Avatar asked Jun 08 '11 05:06

Ulhas Tuscano


1 Answers

using (TransactionScope transaction = new TransactionScope())
{
    bool success = false;
    try
    {
        //your code here
        UpdateTable1();
        UpdateTable2();
        transaction.Complete();
        success = true;
    }
    catch (Exception ex)
    {
        // Handle errors and deadlocks here and retry if needed.
        // Allow an UpdateException to pass through and 
        // retry, otherwise stop the execution.
        if (ex.GetType() != typeof(UpdateException))
        {
            Console.WriteLine("An error occured. "
                + "The operation cannot be retried."
                + ex.Message);
            break;
        }
    }    

    if (success)
        context.AcceptAllChanges();
    else    
        Console.WriteLine("The operation could not be completed");

    // Dispose the object context.
    context.Dispose();    
}
like image 146
Akhil Avatar answered Oct 13 '22 09:10

Akhil