2017-07-31 80 views
0

我是相當新的EF交易,這是用於保存當在TransactionScope中放置時覆蓋SaveChangesAsync?

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

當我保存一個項目,我得到的錯誤:

交易已中止

當我刪除事務範圍保存正常發生!

+0

你爲什麼提到時間戳?這是一個日誌運行操作? –

+0

不,我刪除它,仍然得到相同的錯誤 –

+0

我將TransactionScope移動到重寫的方法,現在它的工作 –

回答

2

您的代碼標記交易完成之前更改完成保存:

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

您需要使用await

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

如果您在上下文是哪裏的await可以恢復上一個不同的線程,你可能還需要指定TransactionScopeAsyncFlowOption.Enabled

+0

問題是,這種方法把'out string'作爲參數,所以我不能將它標記爲'async'! –

+0

我發佈了完整的代碼 –

+0

然後改變你的返回類型以包含所有'out'參數。 –

相關問題