删除实体框架中的对象及其所有子对象?
我一直试图在这里找到这个问题的答案。似乎有几个人问过类似的问题,但我没有得到答案。我有一个带有一堆子实体的 EF 实体(一对多关系)。我希望能够删除“父”实体并同时删除所有子实体。
有些人提到应该在 EF 模型和数据库(在我的例子中是 Sql Server)上设置“级联删除”。问题是:
- 我完全不知道如何做到这一点(似乎暗示在那些你应该知道的答案中,但抱歉......)
- 我有一种感觉,我以前遇到过类似的问题,并在某处找到了答案这比设置级联删除更简单。我可能是错的,也许这是唯一的方法,但如果有更简单的解决方案,我想知道。
无论哪种情况,如果有一个清晰的示例来说明如何实现此功能,我们将不胜感激!
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.
Some people mention "Cascade Delete" should be set on both EF model and database (Sql Server in my case). The problem is:
- I have absolutely no idea how to do this (seems to be implied in those answers that you should know, but sorry...)
- I have a feeling I've run into a similar problems before and found an answer somewhere that was simpler than setting this Cascade Delete. I may be wrong, maybe it is the only way, but if there is a simpler solution I'd like to know.
In either case, a clear example of how to get this working would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 SQL Managment Studio 中,转到您的数据库并找到应该有外键的表。向表添加指向另一个表的外键。我假设您知道如何设置外键。在对话框窗口底部的外键设置中,您将看到删除属性。将其设置为级联。这将导致每当删除父行时删除所有相关行。然后在 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.
以下是 MSDN 上的一些相关文档。但请注意,示例中似乎存在错误。使用此配置时,我从 EDMX 设计者那里收到以下错误。
您应该将 OnDelete 属性设置为 Cascade,因为一端将触发另一端的删除。
例如,在涉及客户和订单的关系中,您希望将客户的订单与客户一起删除,则应将客户角色的 OnDelete 属性设置为级联。
请注意,只有已加载到 ObjectContext 中的对象才会受到级联删除的影响。您将依靠在数据库中设置的级联删除来处理任何其他记录。
Here is some relevant documentation on MSDN. Note though that there appears to be an error in the example. I received the following error from the EDMX designer when using this configuration.
You should set the OnDelete property to Cascade for the end will be triggering deletes on the other end.
As an example, in a relationship involving customers and orders where you would like to have a customer's orders deleted along with the customer, you should set the OnDelete property for the Customer role to Cascade.
Note that only objects that have been loaded into the ObjectContext will be affected by a cascading delete. You will be relying on the cascading delete that you set in the database to look after any other records.