使用Entity Framework删除多对多关系

我有三个表学生(studID,fullName,性别……),注册(studID,courseID,日期)和课程(courseID,courseName,…)。 我使用下面的代码删除了包含studID 001的Enroll表中的所有记录,其中有大约三个学生签名的课程。 但是,它只删除一条记录。

using(var context = new DBEntities()) { var _stud = (from s in context.Students where s.studID == "001" select s).FirstOrDefault(); var _course = _stud.Courses.FirstOrDefault(); _course.Students.Remove(_stud); context.SaveChanges(); } 

我在这里想念什么?

谢谢你们的帮助。 这是我解决它的方式:

 using (var context = new DBEntities()) { var student = (from s in context.Students where s.studID == "001" select s).FirstOrDefault(); foreach (Course c in student.Courses.ToList()) { student.Courses.Remove(c); } context.SaveChanges(); } 

我使用下面的代码从Enroll表中删除所有记录

你是在删除入学者还是学生?

 Student student = context.Student.FirstOrDefault(s => s.studID == "001"); if (student!=null) { student.Enrolls.Load(); student.Enrolls.ToList().ForEach(e => context.Enroll.DeleteObject(e)); } 

你试过这段代码:

 var student = context.Students.Where(p => p.studID == "001").ToList(); foreach (var item in student) { if (student != null) { var course = student.Courses.ToList(); if (course != null) { foreach (var item2 in course) { course.Students.Remove(item2); context.SaveChanges(); } } } } 

对于其他寻求此答案的人,您也可以使用include来实现。

 using(var context = new DBEntities()) { // Get student by id var student = context.Students.Include(s => s.Courses).Where(s => s.studID == "001").FirstOrDefault(); if(student.Courses != null) { // Retrieve list of courses for that student var coursesToRemove = stud.Courses.ToList(); // Remove courses foreach (var course in coursesToRemove) { student.Courses.Remove(course); } // Save changes context.SaveChanges(); } }