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
: 249 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





1 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





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