I have models:
- Student = (... List CourseList);
- Course = (... List StudentList);
I added students to few different courses and using Entity Framework, I added everything to the database.
Please help me remove student from specific course using EF
I have models:
I added students to few different courses and using Entity Framework, I added everything to the database.
Please help me remove student from specific course using EF
It greatly helps to show your models and code for assistance. I'll take a stab based on your pseudo code:
var course = context.Courses.Include(c => c.Students)
.SingleOrDefault(c => c.CourseID == selectedCourseId);
if (course != null)
{
var studentToRemove = course.Students.SingleOrDefault(s => c.StudentID == selectedStudentId);
if (studentToRemove != null)
{
course.Students.Remove(studentToRemove);
context.SaveChanges();
}
}
It depends a bit if you have configured a one-to-many relationship or a many-to-many relationship
I think every Student
can attend zero or more Courses
, and every Course
can be attended by zero or more Students
: a many-to-many relation ship.
This is configured as follows:
class Student
{
public int Id {get; set;}
// a Student attends zero or more courses:
public virtual ICollection<Course> Courses {get; set;}
}
class Course
{
public int Id {get; set;}
// a Course is attended by zero or more Students:
public virtual ICollection<Student> Students{get; set;}
}
class MyDbContext : DbConter
{
public DbSet<Student> Students {get; set;}
public DbSet<Course> Courses {get; set;}
}
This is all. From this Entity Framework will know you want to design a many-to-many relationship. It will even create and fill the many-to-many junction table for you.
So now you've added some Students and Some Courses. Suppose you want to remove a Student.
using (var dbContext = new MyDbContext())
{
Student studentToRemove = ...
// for example:
Student studentToRemove = dbContext.Students
.Where(student => student.Name == "John Doe")
.FirstOrDefault();
if (studentToRemove != null)
{
dbContext.Students.Remove(studentToRemove);
dbConext.SaveChanges();
}
}
That is all. Entity Framework will remove the Student
from the Students
table and automatically make sure that he can't be found on any of the Courses
lists. You don't have to do some inner join. Entity Framework knows it is a many-to-many relationship and will do the correct inner join for you