I have a teacher
that has a many-to-many relationship with students
. Now, in the Edit Teacher
method I want to first remove all the students he has, and then add the students that are selected.
This is my code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name")] Teacher teacher, FormCollection form)
{
if (ModelState.IsValid)
{
teacher.Students.Clear();
var students = form["Students"];
foreach (string id in students.Split(','))
{
teacher.Students.Add(db.Students.Find(int.Parse(id)));
}
db.Entry(teacher).State = EntityState.Modified;
db.saveChanges();
}
}
Except the problem is, all the Teacher-Student
relationships are not being removed. What am I doing wrong?
Clear() is not working as you think... EF is a bit pants when doing 'batch' delete... you have to iterate over them and remove one by one. eg You need something like...
foreach (var student in teacher.Students.ToList())
{
db.Remove(student);
}
In this example you need ToList() to create a copy because most of the collection classes don't like it when you delete items from them during enumeration.
Edit: To get values / entities from database do something like
List<Students> students = (from stu in db.Students
where stu.TeacherId = teacher.Id
select stu).ToList();
Then iterate over these and remove as above, eg
foreach (var student in students)
{
db.Remove(student);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.