How to remove relationship between two entities

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.


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.