基础提供程序在打开时失败/该操作对事务状态无效

时间:2016-09-23 11:03:29

标签: c# entity-framework entity-framework-6 transactionscope

这是我的代码

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

&#34; db.SaveChanges()&#34;

发生异常

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

另外,要插入和更新的记录总数是2700,真的不是那么多。但是完成for语句需要花费很多时间(大约10分钟左右)。因为for语句中发生的所有事情实际上都发生在记忆中,所以有人可以解释为什么这需要这么长时间?

1 个答案:

答案 0 :(得分:2)

您可以使用最新的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(); 
        } 
 } 
}