使用实体框架删除多对多关系 [英] Delete Many to Many relationship using Entity Framework

查看:120
本文介绍了使用实体框架删除多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张表Student(studID,fullName,gender ...),Enroll(studID,courseID,date)和Course(courseID,courseName ...)。我使用下面的代码删除了登记表中的所有记录,其中有studID 001,其中大约有三门课程由学生签名。但是,它只会删除一条记录。

  using(var context = new DBEntities())
{
var _stud =(from s in context.Students where s.studID ==001select 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 ==001select s).FirstOrDefault< Student>();
foreach(课程c在student.Courses.ToList())
{
student.Courses.Remove(c);
}
context.SaveChanges();
}


I've three tables Student (studID, fullName, gender...), Enroll (studID, courseID, date) and Course (courseID,courseName, ...). 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. 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();
}

这篇关于使用实体框架删除多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆