Joseph Michael Pesch
VP Programming

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

by 1. December 2013 14:12

When running inside a foreach() statement this error will occur unless you convert the Entity objects into a List.

// Original code that errors:
myFlickr = FlickrAuthentication();
using (FlickrPicsModel.FlickrPicsEntities dbx = new FlickrPicsModel.FlickrPicsEntities())
{
  foreach (FlickrPicsModel.Pic pic in dbx.Pics.Where(t => t.ProcessDate.Value >= MinDate &&
    t.FlickrPhotoId == null))
  {
    pic.FlickrPhotoId = myFlickr.UploadPicture(string.Concat(pic.FilePath, @"\", pic.FileName)
      , pic.FlickrTags, pic.FlickrTags, pic.FlickrTags + ",CS-" + pic.CheckSum.ToString());
    dbx.SaveChanges();
  }
}

// New code converting to IList:

myFlickr = FlickrAuthentication();
using (FlickrPicsModel.FlickrPicsEntities dbx = new FlickrPicsModel.FlickrPicsEntities())
{
  foreach (FlickrPicsModel.Pic pic in dbx.Pics.Where(t => t.ProcessDate.Value >= MinDate &&
    t.FlickrPhotoId == null).ToList())
  {
    pic.FlickrPhotoId = myFlickr.UploadPicture(string.Concat(pic.FilePath, @"\", pic.FileName)
      , pic.FlickrTags, pic.FlickrTags, pic.FlickrTags + ",CS-" + pic.CheckSum.ToString());
    dbx.SaveChanges();
  }
}

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

Tags:

Comments are closed