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

本文关键字:操作 作对 事务 无效 状态 失败 程序 | 更新日期: 2023-09-27 18:08:32

这是我的代码

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

异常发生在"db.SaveChanges() "

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

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

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

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

注意: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(); 
        } 
 } 
}