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();
}


2 comments:

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

    thanx very much Ramil

    ReplyDelete
  2. SISGAIN offers innovative telemedicine app design services in Saudi Arabia, focused on creating intuitive, user-friendly, and secure digital healthcare platforms. Our design approach prioritizes seamless navigation, patient engagement, and a smooth user experience for both patients and healthcare providers.

    ReplyDelete