封装在TransactionScope中时覆盖SaveChangesAsync?

时间:2017-07-31 10:54:19

标签: c# entity-framework transactionscope

我对EF交易相当新,这是用于保存的代码

public bool Save(TbArea area, bool isNew, out string errMsg)
        {
            try
            {
                errMsg = string.Empty;
    using (var oScope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(120)))
                    {
                        try
                        {
                            TbArea oEntity = oContext.TbArea.Where(a => a.AreaCode == area.AreaCode && a.CompanyId == MainClass.SystemCompanyId).FirstOrDefault();
                            if (oEntity != null)
                            {
                                if (isNew) { errMsg = Resources.ResSales.MsgRecordCodeDublicated; return false; }
                                oContext.TbArea.Attach(oEntity);
                                oContext.Entry(oEntity).CurrentValues.SetValues(area);
                            }
                            else
                            {
                                if (!isNew) { errMsg = Resources.ResSales.MsgRecordNotFoundInDB; return false; }
                                oContext.TbArea.Add(area);
                            }

                            oContext.SaveChangesAsync();
                            oScope.Complete();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            oScope.Dispose();
                            errMsg = ex.Message;
                            return false;
                        }
                    }

我覆盖SaveChangesAsync 这样我就可以将ChangeTracker.Entries保存到数据库中。 这是代码的一部分:

    dbContext.AcceptAllChanges();
    logsSet.AddRange(audits);
    int result = 0;
    try
      {
         result = await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
                //scope.Complete(); there was a transaction that I commented out, I thought it might overlaps the original transaction!

          return result;
       }
     catch (Exception ex)
          {
             var m = ex.Message;
             return result;
          }

当我保存项目时,我收到错误:

  

交易已中止

当我删除事务范围时,保存正常进行!

1 个答案:

答案 0 :(得分:2)

您的代码在更改完成保存之前标记了事务已完成:

oContext.SaveChangesAsync();
oScope.Complete();

您需要使用await

await oContext.SaveChangesAsync();
oScope.Complete();

如果您处于await可以在其他线程上恢复的环境中,您可能还需要指定TransactionScopeAsyncFlowOption.Enabled