2016-09-23 61 views
2

这里的状态是我的代码基础提供失败的打开/操作是无效的交易

public static string UpdateEmptyCaseRevierSet() { 
    string response = string.Empty; 
    using (System.Transactions.TransactionScope tran = new System.Transactions.TransactionScope()) { 
     using (var db = new Entities.WaveEntities()) { 
      var maxCaseReviewersSetID = db.CaseReviewerSets.Select(crs => crs.CaseReviewersSetId).Max(); 
      var emptyCHList = db.CaseHistories.Where(ch => ch.CaseReviewersSetID == null && ch.IsLatest == true && ch.StatusID != 100).ToList(); 
      for(int i=0; i < emptyCHList.Count; i++) { 
       var emptyCH = emptyCHList[i]; 
       var newCaseReviewerSET = new Entities.CaseReviewerSet(); 
       newCaseReviewerSET.CreationCHID = emptyCH.CHID; 
       db.CaseReviewerSets.Add(newCaseReviewerSET); 
       emptyCH.CaseReviewerSet = newCaseReviewerSET; 
      } 
      db.SaveChanges(); 
     } 
     tran.Complete(); 
    } 
    return response; 
} 

异常的occures“db.SaveChanges()”

我看到另一篇文章与"it seems I cannot have two connections opened to the same database with the TransactionScope block."相同的错误消息,但我不认为这与我的情况有任何关系。

此外总共插入和更新的记录数是2700,女巫实际上并不是那么多。但是要完成for语句需要花费相当多的时间(大约10分钟左右)。由于for语句中发生的所有事情实际上都发生在内存中,有人可能会解释为什么这会花费这么长时间?

+1

试试用增'交易时间' – Sagar

回答

1

您可以尝试使用最新的db.Database.BeginTransaction API,如下所示。

注:使用foreach代替for

using (var db = new Entities.WaveEntities()) 
    { 
    using (var dbContextTransaction = db.Database.BeginTransaction()) 
     { 
     try 
      { 
      var maxCaseReviewersSetID = db.CaseReviewerSets.Select(crs => crs.CaseReviewersSetId).Max(); 
      var emptyCHList = db.CaseHistories.Where(ch => ch.CaseReviewersSetID == null && ch.IsLatest == true && ch.StatusID != 100).ToList(); 

      foreach(var ch in emptyCHList) { 
       var newCaseReviewerSET = new Entities.CaseReviewerSet(); 
       newCaseReviewerSET.CreationCHID = ch.CHID; 
       db.CaseReviewerSets.Add(newCaseReviewerSET); 
       } 

       db.SaveChanges(); 
       dbContextTransaction.Commit(); 
      } 
    catch (Exception) 
     { 
      dbContextTransaction.Rollback(); 
     } 
} 
} 
+0

这方面的任何反馈? – Sampath

+1

感谢您花时间回复。那么它确实有效(虽然只有插入的工作不是更新,但这是一个不同的问题),但我希望有人向我解释我得到错误的原因以另一种方式。 – user1831795