views:

65

answers:

3

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!!

A: 

You have to go through each StudentObj that references this ClassObj and remove the reference. This is necessary to maintain referential integrity.

Necros
I tried deleting all classes and and all students and then calling entities.SaveChanges() (using two foreach statements and their collections and calling deleteobject inside the loop) and I'm still getting the same error message. Any ideas?
evan
+2  A: 

One solution is to put a cascade (or SET NULL) on the FK and then regenerate your entity model.

Craig Stuntz
Thanks for your answer! I've heard about the cascade delete (assuming that's what you mean?), but my understanding is that would delete all the objects that were related to the one deleted even if those were related to others. Basically in this example if you deleted a class would it delete the students related to that class even if they were also related to another class?
evan
The cascade deletes the *relationship*, not the entity.
Craig Stuntz
cool :), will try!
evan
that did the trick, thanks!
evan
A: 

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.

Mittop
Hahaha, yes you understand me :). Thanks for your answer. How do you delete directly from the junction tables from the entities framework? Is there a way to do what you described without having to work directly with the database?
evan