简体   繁体   English

如何删除与“用户”关联的所有记录?

[英]How can I delete all records associated with a “User”?

I'm using Entity Framework along with the default ASP.NET Membership service. 我正在使用Entity Framework以及默认的ASP.NET Membership服务。 I also have a 3rd table for "profile information". 我还有一个第三个表格,用于“个人资料信息”。 I thought EF would take care of all that internally but it does not. 我以为EF会在内部处理所有内容,但事实并非如此。 When I attempt to delete a user by going to a URL like http://localhost:19506/User/Delete/SomeGUIDhere I get some nasty errors related to the fact that there are foreign key constraints in place. 当我尝试通过转到http://localhost:19506/User/Delete/SomeGUIDhere这样的URL来删除用户时,我得到一些与存在外键约束这一事实有关的令人讨厌的错误。

How can these types of dependencies be managed? 如何管理这些类型的依赖项? Having to keep track of it all kind of defeats the purpose of EF so I'm guessing I'm missing something minor. 不得不追踪它所有类型的失败EF的目的,所以我猜我错过了一些小的东西。

EDIT to include some code I have that is working. 编辑包含我正在使用的一些代码。 I still want to know if there is a better way than what I have below. 我仍然想知道是否有比下面更好的方法。 Seems like it would get out of control really quickly with lots of foreign key dependencies floating around. 看起来它会很快失控,很多外键依赖依赖。

public void DeleteUser(User u)
{
    db.Profiles.DeleteObject(u.Profile);
    db.aspnet_Membership.DeleteObject(u.aspnet_Membership);
    db.Users.DeleteObject(u);
    db.SaveChanges();
}

How can these types of dependencies be managed? 如何管理这些类型的依赖项? Having to keep track of it all kind of defeats the purpose of EF so I'm guessing I'm missing something minor. 不得不追踪它所有类型的失败EF的目的,所以我猜我错过了一些小的东西。

Unfortunately this is still a manual process, and two-fold as @Danny Varod pointed out: 不幸的是,这仍然是一个手动过程,并且@Danny Varod指出了两倍:

  1. In your database, assuming the foreign key relationship has already been established, make sure that the condition "On Delete -> Cascade" is selected. 在数据库中,假设已建立外键关系,请确保选中“在删除 - >级联”条件。 You can change this in SQL Server Management Studio. 您可以在SQL Server Management Studio中更改此设置。

  2. In you EF entity model you also should designate this option on the relationship. 在您的EF实体模型中,您还应该在关系上指定此选项。 For this just select the dotted line between the entities that represents the relationship. 为此,只需选择代表关系的实体之间的虚线。 In the properties you will see the appropriate option for "Cascading Delete" - you should pick delete for the End that has the 1 and not the *. 在属性中,您将看到“Cascading Delete”的相应选项 - 您应该为具有1而不是*的End选择删除。

在此输入图像描述

级联删除概念模型(和db)的关系。

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

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