如何删除两个实体之间的关系 [英] How to remove relationship between two entities

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

问题描述

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

I have two entities, Student and Course. Given a student ID and course ID, I need to remove their relationship (meaning that a student won't take that course anymore) (please note I don't need to remove the student and course themselves, just their relationship).

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

I tried with Students.Courses.Clear(), but it clears every single course and not a specific one. Thank you.

编辑:
在数据库中,学生和课程通过带有两列的StudentCourse表关联: StudentID和 CourseID。

In the database, Student and Course are related through a StudentCourse table with 2 columns: StudentID and CourseID.

我通常会删除该行以删除关系,但是当从数据库生成模型时,它不会为此表创建实体。相反,学生和课程是彼此的导航属性,它们的关联设置为学生课程表。谢谢。

I would normally delete the row to remove the relationship, but when the model was generated from the database, it didn't create an entity for this table. Instead, Student and Course are navigation properties of each other and their Association is set to the StudentCourse table. Thank you.

推荐答案

您将拥有一个学生,一个课程以及诸如已注册课程之类的东西,其中包含该课程和该学生的ID 。

You will have a student, course and something like enrolled course which holds the id of the course and the student. Just delete that record when they drop out or create one when a student enrolls.

在EF中,可能只是这样:

In EF probably something like this:

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

然后提交您的更改。

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

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