使用实体框架删除多对多关系
本文关键字:关系 删除 框架 实体 | 更新日期: 2023-09-27 17:57:50
我有三个表Student(studID,fullName,gender。但是,它只删除一条记录。
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<Student>();
foreach (Course c in student.Courses.ToList())
{
student.Courses.Remove(c);
}
context.SaveChanges();
}
我使用下面的代码从注册表中删除了所有记录
你是在删除招生还是学生?
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();
}
}