Reputation: 1916
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.!!!
Upvotes: 0
Views: 6978
Reputation: 2524
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();
Upvotes: 3
Reputation: 1916
Got a very good solution in this nice Blog.
Solution of my problem:-
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);
var idlist = id.ToArray<EnrollTrainee>();//Added New Line
if (idlist != null)
{
foreach (var a in idlist)
{
EnrollTrainee delete = db.EnrollTrainee.Find(a.id);
db.EnrollTrainee.Remove(delete);
db.SaveChanges();
}
}
k++;
}
}
}
populatelistbox();
return View();
}
Upvotes: 1