如何在Entity Framework中应用事务

6

我有两张表格。我正在使用实体框架更新这些表格。以下是我的代码:

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

如果任何表更新操作失败,则其他操作不应提交,我该如何在Entity Framework中实现此功能?
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();    
}

谢谢您的快速回复。我正在使用执行实体框架数据库操作的WCF服务。在这种情况下,这种方法可以工作吗? - Ulhas Tuscano
是的,TransactionScope可以使代码块具有事务性(可在任何地方使用)。TransactionScope确保对象上下文中的对象更改与消息队列协调。 - Akhil
在 using 块内部不需要一个 transaction.Complete() 语句来防止事务回滚吗? - Anton
抱歉,我忘记了。谢谢Anton指出 :) - Akhil
请注意 Ralph Lavelle 的回答:您不需要使用事务!SaveChanges 方法本身处理事务!至少对于这个例子,使用 TransactionScope 是完全没有意义的!只需在 dbContext 对象上调用 SaveChanges 方法即可。除非在您将要多次调用 SaveChanges 方法的情况下。 - gyousefi

4

使用TransactionScope

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

同时,您需要将 System.Transactions 添加到您的项目引用中。

1

您不需要使用TransactionScope:当您在上下文中调用SaveChanges()时,Entity Framework会自动执行事务。

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

        context.SaveChanges();
    } 
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接