首页 > 解决方案 > 实体框架:从集合中删除所有实体

问题描述

我在 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

如何做到这一点?

谢谢

标签: c#entity-framework

解决方案


您应该要求您的 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.

推荐阅读