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

C#LinqLinq to-Entities

C# Problem Overview


Any ideas on why this could be breaking?

foreach (var p in pp)
{
    ProjectFiles projectFile = (ProjectFiles)p;
    projectFile.Status = Constants.ProjectFiles_ERROR;
    projectFile.DateLastUpdated = DateTime.Now;
    context.SaveChanges();
}

I read that the workaround the issue, is to retrieve the results in one go before the foreach loop.

But didnt I do that? "pp" is the collection of results in my case

C# Solutions


Solution 1 - C#

The pp variable isn't a collection of objects, it's an enumerator that can return objects. While you use the enumerator, the source has to remain open.

Use the ToList method to realise the enumerator into a collection. That will read all items from the enumerator and close the connection to the source, so that you can use the connection for other things.

foreach (var p in pp.ToList())

Solution 2 - C#

A way to get around this is to call .ToList() on your collection before iterating it.

And while you're at it, call context.SaveChanges() only once after the loop exits to speed up the code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick LaMarcaView Question on Stackoverflow
Solution 1 - C#GuffaView Answer on Stackoverflow
Solution 2 - C#Captain KenpachiView Answer on Stackoverflow