1

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?

1
  • _course.Students.Load(); _course.Students.ToList().ForEach(s => context.Student.DeleteObject(s)); this should work. Commented Apr 11, 2014 at 13:49

4 Answers 4

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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));
}

Comments

0

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();
            }
        }           
   }
}     

1 Comment

.Include(p => p.studID) produces error unless replaced by "Course." Even so, it only deletes one record (the top from the list)
0

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.