使用Entity Framework删除多对多关系

时间:2014-04-11 12:34:44

标签: c# entity-framework many-to-many entity-framework-4.1

我有三个表学生(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();
}

我在这里想念什么?

4 个答案:

答案 0 :(得分:5)

谢谢你们的协助。以下是我解决它的方法:

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

答案 1 :(得分:0)

您是否尝试过此代码:

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

答案 2 :(得分:0)

  

我使用下面的代码删除了“注册表”中的所有记录

您是在删除注册人还是学生?

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

答案 3 :(得分:0)

对于寻求此答案的其他人,您也可以使用包含。

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