Delete Many to Many Using Entity Framework and Unit Of Work

I am trying to get list of Student subject from their former class and remove them first so that when promoting the student to the next class, I will get the class subjects and then add them to that student, but all the approaches that I have aren’t working
for me.

this is the student Model

public class Student
    public Student()
        Subjects = new Collection<Subject>();
    // ...
    public virtual ICollection<Subject> Subjects { get; set; }

this is the controller that is posting the action

public ActionResult Promot_Primary(int[] ChkBx, int AliasId)
    if (ModelState.IsValid)
        foreach (var id in ChkBx)
            // this is where am getting all the former class subjects
            var subjectIds = _courseService.GetAllStudentSubject(id)
                                           .Select(x => x.Id); 
            foreach (var item in subjectIds)
                _studentService.RemoveSubject(item, id);
        ViewBag.message = true;

here is the service that is not responding

public void RemoveSubject(int subjectId, int studentId)
    var student = UnitOfWork.Student.GetById(studentId);
    var subject = UnitOfWork.Subject.GetById(subjectId); 

    if (subject == null)


Check if there is any thing that I am missing that is not allowing it to respond to remove… Adding is working perfectly well but Remove isn’t.

Hi 7rippl3m,

Thanks for your post.

You can try change this





More information,you can refer to the following link:

Hope this can be helpful.

Best Regards,


Thanks for the Link but the problem with your answer is that there is no .Delete in EF collection of method thats the problem right now

I just found out that when getting the student by Id inside the service the along with all the properties, the Subject count is 0 that’s why it cant Remove it cause there is nothing inside the subjects property

How can i Include the Subject when getting Student by Id please.

There may not be the subject records for that student.

post UOW and reporsitory with these two entities

There is Subject for the student

Leave a Reply