Entity Framework - “因为会话中有其他线程正在运行,所以不允许创建新事务”

6
我在尝试保存实体框架中的更改时遇到以下错误 -
System.Data.SqlClient.SqlException: 由于会话中有其他线程正在运行,因此不允许新事务。
我已经看到了各种解决此问题的答案,但似乎没有一种能够解决它。基本上,我在我的存储库中在事务内保存大量项目,必须循环遍历多个项目以删除它们并编写审核记录。
我看到的所有其他答案(例如Mark Staffords Answer)都建议声明显式事务(我已经这样做),或者仅在完成循环后调用save changes(由于当前审核方式需要审核ID才能编写审核详细记录,因此这不是一个选项)。
无论何时在删除方法内调用'SaveChanges',都会抛出错误,请参见下文 -
public virtual void Save(DoseReturn oldDoseReturn)
{
    // Get the datetime when the save started
    DateTime saveStartTime = DateTime.Now;
    Dictionary<string, object> oldValues = new Dictionary<string, object>();
    Dictionary<string, object> newValues = new Dictionary<string, object>();

    // Get the object context and open a new transaction
    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
    objectContext.Connection.Open();
    DbTransaction transaction = objectContext.Connection.BeginTransaction();

    // Use the transaction for all updates
    using (transaction)
    {
        if (oldDoseReturn != null)
        {
              IDoseReturnStatusRepository statusRepository = new DoseReturnStatusRepository();
              var list = statusRepository.AsQueryable().Where(x => x.DoseReturnID == oldDoseReturn.DoseReturnID);

              foreach (var item in list)
              {
                  statusRepository.Delete(item, objectRetrievedDateTime, objectContext, saveStartTime, out oldValues, out newValues);
              }

              context.SaveChanges();

              // Get the relevant repository
              IDoseReturnsRepository repository = new DoseReturnsRepository();

              // audit and delete the object
              repository.Delete(oldDoseReturn, objectRetrievedDateTime, objectContext, saveStartTime, out oldValues, out newValues);

              context.SaveChanges();
         }
    }

    try
    {
         // Conduct a final save, then commit the transaction
         context.SaveChanges();
         transaction.Commit();
    }
    catch (Exception ex)
    {
         // An error has occurred, rollback the transaction and close the connection, then present the error
         transaction.Rollback();
         objectContext.Connection.Close();
         throw ex;
    }
    // Close the connection
    objectContext.Connection.Close();
}

public virtual void Delete(T entity, DateTime? objectRetrievedDateTime, ObjectContext objectContext, DateTime saveStartTime, out Dictionary<string, object> oldValues, out Dictionary<string, object> newValues)
    {
        oldValues = new Dictionary<string, object>();
        newValues = new Dictionary<string, object>();

        if (entity == null)
        {
            throw new ArgumentException("Cannot update a null entity.");
        }

        string entityName = entity.GetType().Name;

        if (!objectRetrievedDateTime.HasValue || !this.AuditsAfterRetieval(objectRetrievedDateTime, entityName, entity, saveStartTime))
        {
            this.DeletedEntityAudit(entity, out oldValues, out newValues);

            context.Entry(entity).State = System.Data.EntityState.Deleted;
            this.context.Set<T>().Remove(entity);
            this.Audit(entity, entityName, "Delete", oldValues, newValues, true);
            this.context.SaveChanges();
        }
        else
        {
            throw new Exception("Object cannot be saved as it has been amended in another thread");
        }
    }
1个回答

25

这可能是因为您在尝试保存更改时正在枚举结果。

尝试更改此行:

var list = statusRepository.AsQueryable()
               .Where(x => x.DoseReturnID == oldDoseReturn.DoseReturnID);

至:

var list = statusRepository.AsQueryable()
               .Where(x => x.DoseReturnID == oldDoseReturn.DoseReturnID)
               .ToList();

顺带提一下,在循环内调用.SaveChanges()通常不是一个好主意,因为它通常是一个昂贵的操作(与数据库交互)。


太棒了,已经更改了代码,使其循环遍历需要删除的项目并存储ID列表,然后在第二个循环中通过ID获取并调用删除函数。再次感谢,昨天下午我一直卡在这里。 - user1948635

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接