How to use Entity Framework Transactions

asp.net c# entity-framework

Question

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?

1
6
12/2/2011 9:07:00 PM

Accepted Answer

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();    
}
14
10/23/2015 6:53:00 AM

Popular Answer

use transactionscope

   public bool UpdateTables()
    {
        using (System.Transactions.TransactionScope sp = new System.Transactions.TransactionScope())
        {
            UpdateTable1();
            UpdateTable2();
            sp.Complete();
        }
    }

also you need add System.Transactions to your project refference



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow