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


5 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
  3. Join the most trusted Data Analytics Institute in Delhi and build skills that employers need. Expert mentors, practical training, certification, and job support included.

    ReplyDelete
  4. Looking for the best Java Course in Noida? Join our job-oriented training designed to make you a skilled Java programmer. Learn through real-world projects, coding practice, and live sessions.

    ReplyDelete
  5. Enroll in the best MERN Stack Course in Gurgaon and master full stack web development. Our training covers front-end and back-end technologies with real-time projects, code reviews, and interview preparation.

    ReplyDelete