How to remove relationship between two entities

entity-framework

Question

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).

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

EDIT: 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.

1
11
9/20/2011 7:37:45 PM

Accepted Answer

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.

In EF probably something like this:

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

then submit your changes.

12
2/22/2019 8:11:28 PM

Popular Answer

If you have just StudentID and CourseID and you don't want to load Student and its all Courses from the database you can try this trick:

// 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();
}

This should work with POCOs. I'm not sure if this trick works with EntityObject base entities as well.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow