简体   繁体   English

使用实体框架删除多对多关系

[英]Delete Many to Many relationship using Entity Framework

I've three tables Student (studID, fullName, gender...), Enroll (studID, courseID, date) and Course (courseID,courseName, ...). 我有三个表Student(学生ID,全名,性别...),注册(学生ID,课程ID,日期)和课程(课程ID,课程名称...)。 I used the code below to delete all records from Enroll table with studID 001 where there are about three courses the student signed for. 我使用下面的代码从StudID 001的Enroll表中删除了所有记录,其中学生签署了大约三门课程。 However, it only deletes one record. 但是,它仅删除一条记录。

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();
}

What do I miss here? 我在这里想念什么?

Thank you guys for assisting. 谢谢你们的协助。 Here is how I solved it: 这是我解决的方法:

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();
}

Have you try this code : 您是否尝试过以下代码:

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();
            }
        }           
   }
}     

I used the code below to delete all records from Enroll table 我使用下面的代码从“注册”表中删除了所有记录

Are you deleting enrolls or students? 您要删除注册或学生吗?

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

For others looking to this answer you could also do it using include. 对于寻求此答案的其他人,您也可以使用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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM