如何在Entity框架中应用事务

Ulh*_*ano 6 c# asp.net entity-framework

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

public bool UpdateTables()
{
      UpdateTable1();
      UpdateTable2();
}
Run Code Online (Sandbox Code Playgroud)

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

Akh*_*hil 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();    
}
Run Code Online (Sandbox Code Playgroud)