I am getting an error
New transaction is not allowed because there are other threads running in the session
while running this code in C# entity framework,
foreach (var pFiles in projectFilesList)
{
ProjectFiles projectFile = (ProjectFiles)pFiles;
projectFile.Status = Constants.ProjectFiles_ERROR;
projectFile.DateLastUpdated = DateTime.Now;
context.SaveChanges();
}
//projectFilesList is a list collection
any ideas what can be the issue?
here i think proejctFilesList isn't a collection of objects, it is an Enumerator that can return objects, what you need to do is add .Tolist()
to it, and it should work like
foreach (var pFiles in projectFilesList.ToList())
{
ProjectFiles projectFile = (ProjectFiles)pFiles;
projectFile.Status = Constants.ProjectFiles_ERROR;
projectFile.DateLastUpdated = DateTime.Now;
context.SaveChanges();
}
also, Calling SaveChanges() withing foreach of ToList() or ToArray() is fine for small data sets, but when you have thousands of rows, you will be consuming a large amount of memory.
It's better to load the rows in chunks or keep the SaveChanges() outside the foreach as manish suggested.
You may also get this error when you are calling context.SaveChanges()
inside the
foreach
loop in C#.
It is better to context.SaveChanges()
, once you are done with foreach loop, for example:
foreach (var pFiles in projectFilesList.ToList())
{
ProjectFiles projectFile = (ProjectFiles)pFiles;
projectFile.Status = Constants.ProjectFiles_ERROR;
projectFile.DateLastUpdated = DateTime.Now;
}
//call SaveChanges Here
context.SaveChanges();
It is better make all changes (which Entity Framework will cache) and then save all of the changes at once, by calling SaveChanges() outside the loop.
It will also improve performance, because you will not be calling .SaveChanges() after one small change ( after completing each loop), but it will save all changes at once, which improves performance.
Place context.SaveChanges()
after end of your foreach
loop.
As you are reading results from database, you cannot save it as same time.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly