Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DBTransaction在用于其他方法时关闭_C#_Asp.net_Entity Framework_Transactions - Fatal编程技术网

C# DBTransaction在用于其他方法时关闭

C# DBTransaction在用于其他方法时关闭,c#,asp.net,entity-framework,transactions,C#,Asp.net,Entity Framework,Transactions,我试图在entity framework存储库中对多个不同的insert/update语句使用一个事务,但是每当我将该事务传递给另一个方法时,它将返回为已关闭,请参见下文- ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; objectContext.Connection.Open(); DbTransaction transaction = objectContext.Connection

我试图在entity framework存储库中对多个不同的insert/update语句使用一个事务,但是每当我将该事务传递给另一个方法时,它将返回为已关闭,请参见下文-

ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.Connection.Open();
DbTransaction transaction = objectContext.Connection.BeginTransaction();

using (transaction)
{
      IPersonRepository personRepository = new PersonRepository();
      context.Entry(person).State = System.Data.EntityState.Modified;
      personRepository.Update(person, objectRetrievedDateTime, transaction, objectContext);

      if (existingStatus != null)
      {
           objectContext.CreateObjectSet<tblPersonStatus>().Attach(existingStatus);
           existingStatus.EndDate = DateTime.Now;
           context.Entry(existingStatus).State = System.Data.EntityState.Modified;

           IPersonStatusesRepository repository = new PersonStatusesRepository();
           repository.Update(existingStatus, objectRetrievedDateTime, transaction, objectContext);
      }
}
ObjectContext ObjectContext=((IObjectContextAdapter)context);
objectContext.Connection.Open();
DbTransaction=objectContext.Connection.BeginTransaction();
使用(事务)
{
IPersonRepository personRepository=新的personRepository();
context.Entry(person.State=System.Data.EntityState.Modified;
更新(person、objectRetrievedDateTime、事务、objectContext);
if(existingStatus!=null)
{
objectContext.CreateObjectSet().Attach(existingStatus);
existingStatus.EndDate=DateTime.Now;
context.Entry(existingStatus).State=System.Data.EntityState.Modified;
IPersonStatusesRepository repository=新的PersonStatusesRepository();
更新(现有状态、objectRetrievedDateTime、事务、objectContext);
}
}
当第一个更新方法完成时(personRepository.update),事务有一个错误“base{System.SystemException}={”此SqlTransaction已完成;不再可用。“}”

有没有办法绕过这个问题

EDIT-调用的更新方法如下所示-

public virtual void Update(T entity, DateTime? objectRetrievedDateTime, DbTransaction transaction, ObjectContext objectContext)
    {
        if (entity == null)
        {
            throw new ArgumentException("Cannot update a null entity.");
        }

        using (transaction)
        {
            ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);

            string entityName = entity.GetType().Name;

            if (!objectRetrievedDateTime.HasValue || !this.AuditsAfterRetieval(objectRetrievedDateTime, entityName, entity))
            {
                Dictionary<string, object> oldValues = new Dictionary<string, object>();
                Dictionary<string, object> newValues = new Dictionary<string, object>();

                bool changed = this.EntityHasChanged(entity, entry, out oldValues, out newValues);

                // Check for changes before saving
                if (changed)
                {
                    this.context.SaveChanges();
                    this.Audit(entity, entityName, "Update", oldValues, newValues, false, null);
                }
            }
            else
            {
                throw new Exception("Object cannot be saved as it has been amended in another thread");
            }
        }
    }
公共虚拟无效更新(T实体、日期时间?objectRetrievedDateTime、DbTransaction事务、ObjectContext ObjectContext)
{
if(实体==null)
{
抛出新ArgumentException(“无法更新空实体”);
}
使用(事务)
{
ObjectStateEntry=objectContext.ObjectStateManager.GetObjectStateEntry(实体);
字符串entityName=entity.GetType().Name;
如果(!objectRetrievedDateTime.HasValue | |!this.AuditSafterrieval(objectRetrievedDateTime,entityName,entity))
{
字典oldValues=新字典();
Dictionary newValues=newdictionary();
bool changed=this.EntityHasChanged(实体、条目、out-oldValues、out-newValues);
//保存前检查更改
如果(更改)
{
this.context.SaveChanges();
此.Audit(实体、entityName、“更新”、旧值、新值、false、null);
}
}
其他的
{
抛出新异常(“无法保存对象,因为它已在另一个线程中被修改”);
}
}
}

您的问题在于此构造:

using (transaction)
{
   ...

  Update(transaction, ....)
}

退出时,事务是,因此也将无效。

您的问题在于此构造:

using (transaction)
{
   ...

  Update(transaction, ....)
}

当您退出它时,事务是,因此也变得无效。

只需删除更新方法中的using语句即可

您正在使用

这是如何使用事务的快速存根

using(DbConnection connection = ...)    
{    
    connection.Open();    
    using(DbTransaction transaction = connection.BeginTransaction(...))    
    {
      try{
        ... update ...
        ... another update ...

        transaction.Commit(); 
      }catch(Exception){
       // transaction rolled back here if an Exception is thrown before the call to Commit()
        transaction.Rollback()
      }   
    }     
} // connection closed here

只需删除Update方法中的using语句

您正在使用

这是如何使用事务的快速存根

using(DbConnection connection = ...)    
{    
    connection.Open();    
    using(DbTransaction transaction = connection.BeginTransaction(...))    
    {
      try{
        ... update ...
        ... another update ...

        transaction.Commit(); 
      }catch(Exception){
       // transaction rolled back here if an Exception is thrown before the call to Commit()
        transaction.Rollback()
      }   
    }     
} // connection closed here

您正在代码中的其他地方提交事务,但是没有人能看到它。在您的更新方法中,您正在提交事务我在原始帖子中添加了更新方法,我还检查了调用的任何其他方法,它们都没有提交事务。@user1948635您的更新方法代码错误:您不能使用嵌套的statement@user1948635是的,只为事务使用一个using语句,然后在所有要使用该事务的update方法中就足够了。当您到达using语句的右大括号时,事务将被关闭您正在代码中的其他地方提交事务,但看不到它。在更新方法中,您正在提交事务我在原始帖子中添加了更新方法,我还检查了调用的任何其他方法,它们都没有提交事务。@user1948635您的更新方法代码错误:您不能使用嵌套的statement@user1948635是的,只为事务使用一个using语句,然后在所有要使用该事务的update方法中就足够了。当到达using语句的右大括号时,事务将立即关闭。在我调用rollback之前,不会实际引发异常。在我退出update方法时,有没有办法保持事务打开?不要将其括在using语句中,或者将其移到该方法之外。令人惊讶的是,在我调用rollback之前,该异常实际上不会被抛出。当我退出update方法时,有没有办法保持事务打开?不要将其包含在using语句中,或者将其移到该方法之外。@user1948635乐于帮助:)@user1948635乐于帮助:)