Search code examples
c#entity-frameworkentity

Delete object from an entity with many to many relationship


I am new to Entity Framework so I need help with deleting an object from an entity. I have 2 tables which are in many to many relationship and an association table connecting them in the database. In the model there are only two tables and the association one is presented by navigation properties as this is how the EF works. Now I need to delete an object from the first table by context.EntityName.DeleteObject(object) but when I try to do it the code fails with error "The DELETE statement conflicted with the REFERENCE constraint FK..", which is a foreign key from the association table to the entity, which object I try to delete. I wonder how to fix this. Could you please help me?

Here is how the tables look like:

Teachers

  • Teacher_ID
  • FirstName
  • LastName

TimetableDetail

  • TimetableDetail_ID
  • EducationalDiscipline_ID
  • Weekday
  • StartTime
  • Duration

and the associaion table:

TimetableDetailTeachers

  • Teacher_ID
  • TimetableDetail_ID

And here is how I try to delete it:

TimetablesEntities context = new TimetablesEntities();

TimetableDetail detail = context.TimetableDetails.SingleOrDefault(td => td.TimetableDetail_ID == timetableDetailId);

context.TimetableDetails.DeleteObject(detail);

context.SaveChanges();

Thanks in advance!


Solution

  • You just need to clear the association table by clearing the Teachers list for a particular TimetableDetail. Using your code...

    TimetablesEntities context = new TimetablesEntities();
    
    TimetableDetail detail = context.TimetableDetails.SingleOrDefault(td => td.TimetableDetail_ID == timetableDetailId);
    
    detail.Teachers.Clear();
    
    context.TimetableDetails.DeleteObject(detail);
    
    context.SaveChanges();
    

    The key line being detail.Teachers.Clear()