【问题标题】:How to remove relationship between two entities如何删除两个实体之间的关系
【发布时间】:2011-11-21 07:50:52
【问题描述】:

我有两个实体,学生和课程。给定学生 ID 和课程 ID,我需要删除他们的关系(这意味着学生将不再学习该课程)(请注意,我不需要删除学生和课程本身,只需删除他们的关系)。

我尝试使用 Students.Courses.Clear(),但它会清除每门课程,而不是特定课程。谢谢。

编辑: 在数据库中,Student 和 Course 通过一个包含两列的 StudentCourse 表关联:StudentID 和 CourseID。

我通常会删除该行以删除关系,但是从数据库生成模型时,它没有为该表创建实体。相反,Student 和 Course 是彼此的导航属性,它们的 Association 设置为 StudentCourse 表。谢谢。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您将拥有一个学生、课程和类似已注册课程的内容,其中包含课程和学生的 ID。只需在他们辍学时删除该记录,或在学生注册时创建一个。

    在 EF 中可能是这样的:

    courseToRemove = Student.Courses.FirstOrDefault(c => c.Name == "Mathematics");
    Student.Courses.Remove(courseToRemove);
    

    然后提交您的更改。

    【讨论】:

      【解决方案2】:

      如果您只有StudentIDCourseID,并且不想从数据库中加载Student 及其全部Courses,您可以试试这个技巧:

      // Prepare dummy data
      var student = new Student() { StudentID = ... };
      var course = new Course() { CourseID = ... };
      student.Courses.Add(course);  // Courses must be initialized collection
      
      using (var context = new YourContext())
      {
          context.Students.Attach(student);
          // Now context should believe that it has Student with single Course loaded from the database
          // So remove that link to existing course but don't delete the course       
          student.Courses.Remove(course);
          context.SaveChanges();
      }
      

      这应该适用于 POCO。我不确定这个技巧是否也适用于 EntityObject 基本实体。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-27
        • 1970-01-01
        相关资源
        最近更新 更多