在实体框架中删除对象及其所有子对象? [英] Delete object and all its child objects in Entity Framework?

查看:103
本文介绍了在实体框架中删除对象及其所有子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在这里找到这个问题的答案.似乎有人在问类似的问题,但我没有得到答案.我有一个EF实体,带有一堆子实体(一对多关系).我希望能够删除父"实体,并同时删除所有子实体.

I've been trying to find the answer to this question here. Several people seem to ask similar things, but I don't get the answers. I have an EF entity with a bunch of child entities (one-to-many relationship). I want to be able to delete the "parent" entity and have all the child entities deleted at the same time.

有人提到应该在EF模型和数据库上设置级联删除"(在我的例子中是Sql Server).问题是:

Some people mention "Cascade Delete" should be set on both EF model and database (Sql Server in my case). The problem is:

  1. 我绝对不知道如何执行此操作(似乎应该在您应该知道的答案中隐含,但对不起...)
  2. 我觉得我之前也遇到过类似的问题,并在某个地方找到了比设置级联删除"更简单的答案.我可能是错的,也许这是唯一的方法,但是如果有一个更简单的解决方案,我想知道.

无论哪种情况,都将非常感谢您提供一个清晰的示例来说明如何实现此功能!

In either case, a clear example of how to get this working would be greatly appreciated!

推荐答案

在SQL Managment Studio中,转到您的数据库并找到应该有外键的表.将外键添加到指向另一个表的表.我假设您知道如何设置外键.在对话框窗口底部的外键设置中,您将看到Delete属性.将其设置为Cascade.每当父行被删除时,这将导致所有从属行被删除.然后去并在Visual Studio中更新您的数据模型.现在应该为您完成所有设置.

In SQL Managment Studio go to your database and find the table where there should be a foreign key. Add a foreign key to the table pointing to the other table. I assume you know how to setup a foreign key. In the foreign key setup at the bottom of the dialog window you'll see a Delete property. Set it to Cascade. This will cause any dependent rows to be deleted whenever the parent row is deleted. Then go and update your data model in Visual Studio. Everything should be setup for you now.

这篇关于在实体框架中删除对象及其所有子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆