开发者

Delete an object with a many to many relationship from the entities framework?

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 d开发者_高级运维o? Thanks for your help!!


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜