jason jason - 18 days ago 7
C# Question

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

I have this simple code :

foreach(var myvar in _sdb.Vars)
{
myvar.Area= AreaCheck(myvar);

_sdb.Entry(myvar).State = System.Data.Entity.EntityState.Modified;
_sdb.SaveChanges();
}


When I run this code I get this exception :


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


I googled the problem, one of the answers told me to change this line :

foreach(var myvar in _sdb.Vars)


To this line :

foreach(var myvar in _sdb.Vars.ToList())


But when I did it, the code didn't work at all. How can I make this work? Thanks.

Answer

Save after iterations like below

using (var _sdb = new MyContext())
{
    foreach (var myvar in _sdb.Vars)
    {
        // Change myvar
    }
     //save at the end
    _sdb.SaveChanges();
}
Comments