简体   繁体   中英

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

I'm using Entity Framework along with the default ASP.NET Membership service. I also have a 3rd table for "profile information". I thought EF would take care of all that internally but it does not. 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.

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.

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.

Unfortunately this is still a manual process, and two-fold as @Danny Varod pointed out:

  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.

  2. In you EF entity model you also should designate this option on the relationship. 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 *.

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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