如何删除与“用户”相关联的所有记录? [英] How can I delete all records associated with a "User"?

查看:150
本文介绍了如何删除与“用户”相关联的所有记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架以及默认的ASP.NET成员资格服务。我还有一个第三张表,用于个人资料信息。我认为EF会照顾所有的内部,但它没有。当我尝试通过转到 http:// localhost:19506 / User / Delete / SomeGUIDhere 之类的URL删除用户时,我会发现一些令人讨厌的错误,与是外键约束。



这些类型的依赖关系如何被管理?不得不跟踪它,所有类型的失败的EF的目的,所以我猜,我错过了一些小的。



编辑包括我正在工作的一些代码。我还想知道是否有比我以下更好的方法。似乎这样会很快失去控制,很多外键依赖关系浮动。

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


解决方案


这些类型的依赖关系如何管理
?不得不跟踪它
所有类型的失败EF
的目的,所以我猜想我错过了一些
次要的。


不幸的是,这仍然是一个手动过程,而@Danny Varod指出,双重的两倍:


  1. 在您的数据库中,假设外键关系已经建立,请确保选择了On Delete - > Cascade条件。您可以在SQL Server Management Studio中进行更改。


  2. 在您的EF实体模型中,您还应该在关系上指定此选项。为此,只需选择表示关系的实体之间的虚线。在属性中,您将看到级联删除的相应选项 - 您应该选择具有 1 而不是*的结尾的删除。



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 *.

这篇关于如何删除与“用户”相关联的所有记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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