6

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?

4 Answers 4

14
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();    
}
5
  • Thanx for your quick reply. I am using WCF service which performs database operation using entity framwork. eill this method work in this scenario? Jun 8, 2011 at 5:23
  • Yes, TransactionScope makes a code block transactional (used anywhere). The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue.
    – Akhil
    Jun 8, 2011 at 5:28
  • Don't you need a transaction.Complete(); statement inside the using block to prevent the Transaction from rolling back?
    – Anton
    Jun 8, 2011 at 5:45
  • Sorry, i forgot. Thanks Anton, for Pointing it out :)
    – Akhil
    Jun 8, 2011 at 5:47
  • Please attention to Ralph Lavelle's answer: You don't need to use transaction! The SaveChanges method itself handles transaction! At least for this example using a TransactionScope is totally meaningless! Simply call SaveChanges methood on the dbContext object. Unless in scenarios when you are going to call SaveChanges method multiple times.
    – gyousefi
    Oct 27, 2019 at 5:19
4

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

1

You don't need to use a TransactionScope: Entity Framework automatically enforces a transaction when you call SaveChanges() on your context.

public bool UpdateTables()
{
    using(var context = new MyDBContext())
    {
        // use context to UpdateTable1();
        // use context to UpdateTable2();

        context.SaveChanges();
    } 
}
0

You can do something like this....

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead }))
                {
                    using (YeagerTechEntities DbContext = new YeagerTechEntities())
                    {
                        Category category = new Category();

                        category.CategoryID = cat.CategoryID;
                        category.Description = cat.Description;

                        // more entities here with updates/inserts
                        // the DbContext.SaveChanges method will save all the entities in their corresponding EntityState

                        DbContext.Entry(category).State = EntityState.Modified;
                        DbContext.SaveChanges();

                        ts.Complete();
                    }
                }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.