jason
jason

Reputation: 7164

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.

Upvotes: 2

Views: 5572

Answers (1)

Damith
Damith

Reputation: 63065

Save after iterations like below

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

Upvotes: 4

Related Questions