【问题标题】:How to update many to many relationship in Entity Framework如何更新实体框架中的多对多关系
【发布时间】:2018-03-09 06:47:25
【问题描述】:

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

【问题讨论】:

  • 请勿张贴源代码的屏幕截图 - 将代码本身张贴在此处,并正确格式化以突出显示语法。

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


【解决方案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 实体框架时,都会知道需要与联结表进行联接。

这可以在不使用属性或 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();
}

简单的祝你好运!

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多