aby
aby

Reputation: 830

Delete Many to Many relationship using Entity Framework

I've three tables Student (studID, fullName, gender...), Enroll (studID, courseID, date) and Course (courseID,courseName, ...). I used the code below to delete all records from Enroll table with studID 001 where there are about three courses the student signed for. However, it only deletes one record.

using(var context = new DBEntities())
{    
var _stud = (from s in context.Students where s.studID == "001" select s).FirstOrDefault();
                var _course = _stud.Courses.FirstOrDefault();
                _course.Students.Remove(_stud);
context.SaveChanges();
}

What do I miss here?

Upvotes: 1

Views: 12628

Answers (4)

Victor LG
Victor LG

Reputation: 646

For others looking to this answer you could also do it using include.

using(var context = new DBEntities())
{    
    // Get student by id
    var student = context.Students.Include(s => s.Courses).Where(s => s.studID == "001").FirstOrDefault();

    if(student.Courses != null)
    {
        // Retrieve list of courses for that student
        var coursesToRemove = stud.Courses.ToList();

        // Remove courses
        foreach (var course in coursesToRemove)
        {
            student.Courses.Remove(course);
        }

        // Save changes
        context.SaveChanges();
    }
}

Upvotes: 0

Nayeem Mansoori
Nayeem Mansoori

Reputation: 831

Have you try this code :

var student = context.Students.Where(p => p.studID == "001").ToList();
foreach (var item in student)
{
    if (student != null)
    {
        var course = student.Courses.ToList();
        if (course != null)
        {
            foreach (var item2 in course)
            {         
                course.Students.Remove(item2);
                context.SaveChanges();
            }
        }           
   }
}     

Upvotes: 0

aby
aby

Reputation: 830

Thank you guys for assisting. Here is how I solved it:

using (var context = new DBEntities())
{
    var student = (from s in context.Students where s.studID == "001" select s).FirstOrDefault<Student>();               
    foreach (Course c in student.Courses.ToList())
    {
        student.Courses.Remove(c);
    }
    context.SaveChanges();
}

Upvotes: 5

Andrew
Andrew

Reputation: 3816

I used the code below to delete all records from Enroll table

Are you deleting enrolls or students?

Student student = context.Student.FirstOrDefault(s => s.studID == "001");
if (student!=null)
{
    student.Enrolls.Load();
    student.Enrolls.ToList().ForEach(e => context.Enroll.DeleteObject(e));
}

Upvotes: 0

Related Questions