c# - 实体框架:从集合中删除所有实体
问题描述
我在 ASP.NET MVC 应用程序中使用 Identity。
我的身份模型是(涉及部分):
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Group> Groups { get; set; }
}
public class Group
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set;
}
我得到了这样的用户:
ApplicationUser signedUser = UserManager.FindById(model.Id);
现在我想简单地删除所有Group
这个签名用户。我尝试了一个 foreach 循环,但当然随着集合被修改,它不起作用。我还没有RemoveAll()
方法signedUser.Groups
。
如何做到这一点?
谢谢
解决方案
您应该要求您的 unitOfWork 为您完成这项工作:
unitOfWork.Groups.RemoveRange(signedUser.Groups);
或者,如果您更喜欢直接使用 dbset:
foreach(var group in signedUser.Groups)
{
db.Entry(group).State = EntityState.Deleted;
}
db.SaveChanges(); //After all the customer is deleted, Commit.
推荐阅读
- tensorflow - 尝试在 Tensorflow 中可视化激活
- javascript - 传递数据以填充子组件时,映射不是函数
- android - 点击每颗牙齿的 JAW 设计
- c# - 从 Windows 表单 C# 中的 Modbus EasyModbus.dll 库读取 FT300 传感器数据时出现问题
- java - Apache POI - 读取 OutlookMessage 中添加的用户属性
- javascript - 比较 javascript 或 jquery 中的 2 个项目
- cloud - 所有 Watson 服务都可以在 Lite 帐户中使用吗?
- node.js - node-ts 显示“错误 TS2304:找不到名称 '__DEV__'”
- google-kubernetes-engine - GKE-On-Prem 安装
- python - Numpy std(标准差)函数奇怪的行为