When trying to execute SaveChanges on a Entitiy Framework datacontext, I was getting the following error: There is already an open DataReader associated with this Command which must be closed first The problem was caused by the location of the SaveChanges call. The code called the method inside a ForEach loop that iterates through a result returned from a query. Because of the iteration the datacontext’s connection was on read mode and thus did not allow me to call the update. To fix it I moved the SaveChanges call outside the ForEach loop (when the read was completed: var records = EFDataRepository.GetAll ().Where(r => r.CreatedOn < cutoff_date); foreach (var record in records) { workflow.WorkAndUpdate(record); //repo.SaveChanges(); //do not put it here, you are still iterating over the results in read mode } repo.SaveChanges();
A blog about real-world software engineering and development problems and solutions.