c# - 从 Entity Framework 中删除具有多对多关系的对象?

标签 c# entity-framework asp.net-mvc-2

我在数据库中有两个对象(类(class)、学生)具有多对多关系(使用简单的联结表)。我已经弄清楚如何正确地将新对象添加到表中,现在我想删除一个对象。

我一直在尝试以下方法:

// (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();

这给出了错误:

"The DELETE statement conflicted with the REFERENCE constraint \"FK_JunctionClassObjsStudents_Students\".

其中 JunctionClassObjsStudents 是联结表的名称,它在类(class)和学生表之间创建多对多关系。

我需要做什么?感谢您的帮助!!

最佳答案

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

关于c# - 从 Entity Framework 中删除具有多对多关系的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410020/

相关文章:

c# - 使用 Entity Framework 的最佳比较算法

c# - 在 init 上构建数据库时获取外键的 SqlException

asp.net-mvc-2 - 安装asp.mvc 2 beta nunit项目模板不受信任的组件错误

C# MVC2 : How to get the selected value of a dropdownlist

c# - 干净的代码 : Readable Dependency Injection suggestions?

c# - 非直系亲属类的调用方法

c# - 在本地 IIS 上托管的 WCF 服务应用程序和 MVC4 应用程序(非快速)抛出连接字符串错误

model-view-controller - MVC2 如何<%: tag different to <%=

c# - 毫无意义的单元测试

c# - 如何从 C# 中删除 robo-comments 和#region?