如何更新Entity Framework中的多对多关系

时间:2018-03-09 06:47:25

标签: asp.net-mvc-4 entity-framework-6 ef-code-first many-to-many

enter image description here

如图所示,我在studentscourses之间存在多对多关系。 我想更新给定学生的课程(前student Id = 10选择了Id 2和6的两门课程)。我想删除学生ID 10的课程ID 6并添加新课程,比如Id = 3.

我在ASP.NET MVC 4中使用了实体框架6的代码优先方法。

任何人都可以帮忙解决这个问题吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

您的规范并未明确说明您对“删除课程”一词的含义:您是否要从数据库中删除课程,因此该课程不再存在?或者您希望您的学生停止学习本课程吗?

我将描述两者,因此我有一个有3门课程的学生:

  • Id = 2:不会改变;学生已经学习了本课程并将继续学习本课程
  • Id = 6:学生将停止学习本课程;其他学生可能仍在学习本课程
  • Id = 7:课程将从数据库中删除

此外你有:

  • Id = 3:学生将开始学习本课程

实体框架中的多对多

如果您根据Entity Framework Code First many-to-many conventions配置了多对多关系,您将获得与以下类似的内容:

class Student
{
    public int Id {get; set;}

    // every Student attends zero or more Courses (many-to-many)
    public virtual ICollection<Course> Courses {get; set;}

    ... // other properties 
}

class Course
{
    public int Id {get; set;}

    // every Course is attended by zero or more Students
    public virtual ICollection<Student> Students {get; set;}

    ... // other properties
}

public SchoolContext : DbContext
{
     public DbSet<Student> Students {get; set;}
     public DbSet<Course> Courses {get; set;}
}

这就是实体框架需要知道您想要在学生和课程之间配置多对多关系的全部内容。实体框架将为您创建包含学生和课程外键的联结表。每当您访问ICollections实体框架时,都会知道需要使用联结表进行连接。

这可以在不使用Attributes或Fluent Api的情况下完成。只有在您想要偏离约定时才需要这些,例如,如果您需要不同的表名或列名。

回到你的问题

我们有以下ID:

int idStudent = 10;
int idCourseToStartFollowing = 3;
int idCourseToStopFollowing = 6;
int idCourseToRemoveFromDb = 7;

using (var dbContext = new SchoolContext())
{
    // Fetch the Student to update (has id 10)
    Student studentToUpdate = dbContext.Students.Find(idStudent);

    // this student starts following Course with Id 3
    Course courseToStartFollowing = dbContext.Courses.Find(idCourseToStartFollowing);
    studentToUpdate.Courses.Add(courseToStartFollowing);

    // this student stops following Course with Id 6
    Course courseToStopFollowing = dbContext.Courses.Find(idCourseToStopFollowing);
    StudentToUpdate.Courses.Remove(courseToStopFollowing);

    // Remove Course with Id 7 from the database
    Course courseToRemove = dbContext.Find(idCourseToRemove);
    dbContext.Remove(courseToRemove);

    dbContext.SaveChanges();
}

简单的纪念活动!