简体   繁体   English

从实体框架中删除具有多对多关系的对象?

[英]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. 其中JunctionClassObjsStudents是联结表的名称,它创建了类和学生表之间的多对多关系。

What do I need to do? 我需要做什么? Thanks for your help!! 谢谢你的帮助!!

一种解决方案是在FK上放置级联(或SET NULL ),然后重新生成实体模型。

Assuming I have understood you correctly (and that is a big assumption)... 假设我理解正确(这是一个很大的假设)......

Class Table -> Class_Student_Junction Table <- Student Table 类表 - > Class_Student_Junction表< - 学生表

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. 我想到的问题是你制作的Junction Table,它有约束。 Without putting it into code I would say... 没有把它放入代码我会说......

Step 1: Note the Key of the Class you want to delete 第1步:记下要删除的类的键

Step 2: Delete all from the junction tables where the foreign key for the classes equals the class from step 1. 步骤2:从联结表中删除所有类的外键等于步骤1中的类。

Step 3: Delete the class record from the Classes table. 第3步:从Classes表中删除类记录。 There should be no key violations in that order. 该顺序不应存在任何严重违规行为。

You have to go through each StudentObj that references this ClassObj and remove the reference. 您必须StudentObj引用此ClassObj每个ClassObj并删除引用。 This is necessary to maintain referential integrity. 这对于保持参照完整性是必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM