删除 LINQ to EF 中的关联数据
我是 LINQ 和 EF 的新手,我有一个关于我正在开发的论坛的快速问题。这个论坛上有主题,每个主题都有相关的回复。我假设 EF 会看到该约束,并且在删除主题时也会删除关联的回复。相反,它会引发约束错误。有没有一种简单的方法可以删除所有关联的回复,而无需循环遍历它们并将每个回复标记为删除?
例如,在 SQL 中我只会做这样的事情:
DELETE FROM topic_replies WHERE TopicID='999'
DELETE FROM topics where TopicID='999'
但在 EF 中,我知道这样做的唯一方法是:
Topic topic = //LINQ to get topic.
foreach (Reply reply in topic.Replies)
{
dbEntity.Replies.DeleteObject(reply);
}
dbEntity.Topics.DeleteObject(topic);
如果这是我必须做的,我想这很好。只是好奇是否有更好的方法。提前致谢。
I am new to LINQ and EF and I have a quick question about a forum I am developing. On this forum there are topics, and each topic has associated replies. I assumed that EF would see the constraint and when deleting the topic would also delete the associated replies. Instead it throws a constraint error. Is there an easy way to delete all associated replies without looping through them and marking each one for deletion?
For instance, in SQL I would just do something like this:
DELETE FROM topic_replies WHERE TopicID='999'
DELETE FROM topics where TopicID='999'
But in EF, the only way I know to do this is:
Topic topic = //LINQ to get topic.
foreach (Reply reply in topic.Replies)
{
dbEntity.Replies.DeleteObject(reply);
}
dbEntity.Topics.DeleteObject(topic);
I guess this is fine if this is what I have to do. Just curious if there is a better way. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 EF 架构中的所有者对象中设置级联删除。
看看 http://codepolice.net/2008/12/ 16/级联删除实体框架/
You can set up cascade on delete in owner object in EF schema.
Look at http://codepolice.net/2008/12/16/cascade-delete-in-entity-framework/
在您的数据库中级联删除这些表...然后,当您删除父表时,数据库将处理子表的删除。
级联是外键的一部分
示例
如果您使用 SQL Server
现在基本上就是这样的;如果我删除一个人,那么数据库将删除与该人相关的所有地址
In your database Cascade your deletes for these tables...Then when you delete the parent the database will handle the deletion of the child.
Cascading is part of the foreign key
Example
If your using SQL Server
Now basically what this says is; If i delete a person then the database will delete all addresses that are related to that person
请查看:
创建、添加、修改和删除对象(请阅读级联删除规则)关系):
级联删除和 1-to-1(或 1-to-0..1)关系
Check this out:
Creating, Adding, Modifying, and Deleting Objects (read Cascade Delete Rules on Relationships):
Cascade Delete and 1-to-1 (or 1-to-0..1) Relationships