How to use Entity Framework Transactions

asp.net c# entity-framework

Question

I've got two tables. I am using entity framework to update those tables. This is my code.

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

How can I prevent subsequent database update operations from being committed if one fails 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

employ transactionscope

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

also, System.Transactions has to be included to your project reference.



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