首页 > 解决方案 > SQL Server 和实体框架:事务在一个用例中失败

问题描述

我在我的代码中使用 C#、SQL Server、Entity Framework 6。在表中插入记录时出现异常,但记录已插入表中。

在执行 operation1 时出现以下错误:

System.Data.SqlClient.SqlException:超时已过期。在操作完成之前超时时间已过或服务器没有响应。
该语句已终止。

System.ComponentModel.Win32Exception:等待操作超时

这个问题很少发生。

我的代码如下所示:

Public Void UploadData(Request request)
{
    // Creating db context.
    // Creating TransactionScope object.
    TransactionOptions _oTransactionOptions = new TransactionOptions();
    oTransactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
    oTransactionOptions.Timeout = new TimeSpan(hour, min, sec);

    TransactionScope  TransactionScope = new TransactionScope(TransactionScopeOption.Required, oTransactionOptions);

    try
    {
        // Doing operation1
        // Doing operation2
        // Doing operation3
        // Doing operation4

        TransactionScope.Complete();
        TransactionScope.Dispose();
    }
    catch (Exception ex)
    {
         TransactionScope.Dispose();
          // logging error.
    }
    finally
    {
         // Disposing context.
    }
}

标签: c#sql-serverentity-framework-6

解决方案


推荐阅读