New transaction is not allowed because there are other threads running in the session Linq to Entity Mvc C#

I am Using Linq to Entity MVC and when I am trying to delte records from database I am getting this Exception.

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

My code:

if (Request.Form["Enroll"] != null)
{
    string[] selected = Request.Form["Enroll"].Split(',');

    if (selected != null)
    {
        if (selected.Count() != 0)
        {
            int k = 0;
            foreach (var item in selected)
            {
                var TraineeId = Convert.ToInt32(item[k].ToString());
                var sessionid = Convert.ToInt32(Session["user"].ToString());

                var id = db.EnrollTrainee.Where(i => i.TraineeID == TraineeId
                                                && i.TrainerID == sessionid);

                if (id != null)
                {
                    foreach (var a in id)
                    {
                        //db.Database.Connection.Close();
                        EnrollTrainee delete = db.EnrollTrainee.Find(a.id);
                        db.EnrollTrainee.Remove(delete);
                        db.SaveChanges();   //Getting Exception Here                                        
                    }
                }
                k++;
            }
        }
    }
    populatelistbox();
    return View();
}

Please Help.!!! Thanks in Advance.!!!

Answers


In my case, calling the SaveChanges() less often in nested loops solves the problem:

//produces error 
foreach(...) {
    foreach(...) {
       ...
       db.SaveChanges();
    } }

this is my solution

//does not produce error
foreach(...) {
    foreach(...) {
       ...
    }
}
db.SaveChanges();

Need Your Help

WPF (c#) combobox updating selected displayed item

c# wpf combobox

In my application, i have a combobox. It uses as an item, a name(string) and an ID(int)

How do I control which Canvas layer draws first (JCanvas)

jquery-plugins canvas html5-canvas jcanvas

In the code below I have two Canvas layers one text and one image, the issue I'm having is controlling which layer draws first. When the page is loaded the text may draw above or blow the image, it