开发者

How to remove relationship between two entities

开发者 https://www.devze.com 2023-04-06 00:34 出处:网络
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 re

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 a开发者_StackOverflow社区nd 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消