当包含在 TransactionScope 中时覆盖 SaveChangesAsync?

Overriding SaveChangesAsync when enclosed inside 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;
          }

当我保存项目时,出现错误:

the transaction has aborted

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

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

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

您需要使用await:

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

如果您处于 await 可以在不同线程上恢复的上下文中,您可能还需要指定 TransactionScopeAsyncFlowOption.Enabled.