Wednesday, July 27, 2011

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

Task: Resolve error.
Solution: Use new context to update item in iteration.

Explanation:
This exception occurs in the following code:
C#
MyContext db=new MyContext();
var ListOfEntities=from p in db.Entity select p;
foreach(var item in ListOfEntities)
{
    item.Text="Changed!";
    db.SaveChanges();
}


In the following example it will be OK:


C#
MyContext db=new MyContext();
var ListOfEntities=from p in db.Entity select p;
foreach(var item in ListOfEntities)
{
    MyContext anotherDB =new MyContext();
    var MyItem=(from p in anotherDB where p.ID=item.ID select p).FirstOrDefault();
    MyItem.Text="Changed!";
    anotherDB.SaveChanges();
}


1 comment:

  1. I ran into the same problem and this solution helped me solve the issue at hand.

    thanx very much Ramil

    ReplyDelete