Delete Many to Many relationship using Entity Framework

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

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

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

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

  1. Caden

    • 2017/11/29

    asp.net-core-mvc - I'm using Entity Framework Core in an ASP.NET Core application. I want to be able to delete the joining linking row in a 

  2. Hudson

    • 2017/7/16

    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.

  3. Timothy

    • 2017/2/13

    After searching I've found solution.To delete entity from many-to-many relationship you need load the related navigation property In my case 

  4. Ward

    • 2017/1/17

    "The association between entity types 'Case' and 'EmployeeCase' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes." Here I don't need a Case or an Employee deleted. I just need to delete the join record.

  5. Keith

    • 2016/8/15

    SaveChanges();. The Remove(badge) returns false and I cannot profile this as I am using SQL Compact 4.0. Could this be a cascade delete 

  6. Sutton

    • 2019/7/10

    Entity Framework will create Books, Categories and also the joining table CategoryBooks in the database. The CategoryBooks table will include the PK (Primary Key) of both tables Book_BookId & Category_CategoryId. Using Data Annotations. To configure many-to-many relationship Using Data Annotations, you need to create the Join Table in the model.

  7. Duke

    • 2016/4/1

    Is it possible to add or remove using disconnected entities under this create a joining entity for many-to-many relationships in future.

  8. Beau

    • 2020/6/5

    There are no default conventions available in Entity Framework Core which automatically configure a many-to-many relationship. You must configure it using Fluent API. Fluent API. In the Entity Framework 6.x or prior, EF API used to create the joining table for many-to-many relationships.

  9. Taylor

    • 2016/1/29

    Hi All, I am trying to remove an object from a collection in entity framework, but unfortunately my code is failing.

  10. Carson

    • 2020/11/4

    Many-to-many relationships are represented in the database with a table holding the foreign keys of both sides in the relationship. What you attempt to do, is attempting to change the key of an object, but a reference is still held in the foreign key table, leading to a constraint violation - as the value in the N-N table has not been updated

  11. Hall

    • 2018/6/18

    Learn what is cascading delete in EF 6 code-first approach and how to turn it off. Cascade Delete in One-to-Many Relationships.

  12. Keenan

    • 2016/8/9

    The ability to configure many-to-many relationships was introduced in EF Core 5.0, for previous version use the following approach. Indirect many-to-many relationships You can also represent a many-to-many relationship by just adding the join entity type and mapping two separate one-to-many relationships.

  13. Branson

    • 2019/1/17

    Removing a link to an entity that is already in the navigation property collection you simply remove that entity instance from the collection.

  14. Frederick

    • 2017/2/28

    A many-to-many relationship is defined in code by the inclusion of collection properties in each of the entities - The Categories property in the Book class, 

  15. Kyree

    • 2020/1/5

    In this post I'll show you how to create many-to-many relationships and how to use them in EF Core. The model. Simple and practical example of 

Comments are closed.

Recent Posts