如何在Entity框架中应用事务

时间:2011-06-08 05:04:13

标签: c# asp.net entity-framework

我有两张桌子。我正在使用实体框架更新这些表。这是我的代码

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

如果任何表更新操作失败,则不应提交其他如何在实体框架中实现此目的?

4 个答案:

答案 0 :(得分: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();    
}

答案 1 :(得分:4)

使用transactionscope

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

您还需要将System.Transactions添加到项目引用

答案 2 :(得分:0)

您不需要使用TransactionScope:当您在上下文中调用SaveChanges()时,实体框架会自动强制执行事务。

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

        context.SaveChanges();
    } 
}

答案 3 :(得分:0)

你可以这样做......

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();
                    }
                }