New transaction is not allowed because there are other threads running in the session


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?

 


Asked by:- vikas_jk
3
: 5624 At:- 6/11/2017 7:39:36 AM
C# asp.net mvc linq

did you tried putting your context.SaveChanges(); outside freach loop? 2
By : manish - at :- 6/11/2017 7:50:51 AM





2 Answers
profileImage Answered by:- pika

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.

2
At:- 6/11/2017 11:41:49 AM
good answer, thank you 0
By : vikas_jk - at :- 6/11/2017 11:46:27 AM


profileImage Answered by:- bhanu

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.

0
At:- 4/14/2021 8:28:19 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use