Reputation: 4550
I have two objects (class, student) in a database with a many to many relationship (using a simple junction table). I've figured out how to correctly add new objects to tables, and now I'd like to delete an object.
I've been trying the following:
// (a classobj with id==1 does exist)
ClassObj cl = (from c in entities.ClassObjs where c.ClassID == 1 select c).First();
entities.ClassObjs.DeleteObject(cl);
entities.SaveChanges();
Which gives the error:
"The DELETE statement conflicted with the REFERENCE constraint \"FK_JunctionClassObjsStudents_Students\".
Where JunctionClassObjsStudents is the name of the junction table which creates the many to many relationship between classes and students tables.
What do I need to do? Thanks for your help!!
Upvotes: 3
Views: 1429
Reputation: 66
Assuming I have understood you correctly (and that is a big assumption)...
Class Table -> Class_Student_Junction Table <- Student Table
It seems to me that you would need to do this in two steps. The problem in my mind is the Junction Table you made, which has constraints. Without putting it into code I would say...
Step 1: Note the Key of the Class you want to delete
Step 2: Delete all from the junction tables where the foreign key for the classes equals the class from step 1.
Step 3: Delete the class record from the Classes table. There should be no key violations in that order.
Upvotes: 1
Reputation: 126547
One solution is to put a cascade (or SET NULL
) on the FK and then regenerate your entity model.
Upvotes: 2
Reputation: 3034
You have to go through each StudentObj
that references this ClassObj
and remove the reference. This is necessary to maintain referential integrity.
Upvotes: 0