I am trying to use a single transaction for multiple different insert/update statements in my entity framework repository, however whenever I pass the transaction to a different method it is returned as closed, see below -
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);
}
}
By the time the 1st update method is finished (personRepository.Update), the transaction has an error of "base {System.SystemException} = {"This SqlTransaction has completed; it is no longer usable."}"
Is there any way to get around this?
EDIT - The update method which is called looks like this -
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");
}
}
}