[英]What's the proper way to delete entities in Entity Framework?
I'm having a hard time deleting an object tree. 我很难删除对象树。 My model doesn't use any kind of built-in cascade deletion mechanism, so I have to perform the explicit deletion of each of the related entities.
我的模型不使用任何内置的级联删除机制,因此我必须对每个相关实体执行显式删除。
The entity I want to delete has 3 levels of indirection (navigation properties) 我要删除的实体具有3个间接级别(导航属性)
class Parent
{
public ICollection<Child> Children { get; set; }
}
class Child
{
public ICollection<Grandchild> Grandchildren { get; set; }
}
public class Grandchild
{
}
my DbContext is 我的DbContext是
public class Context
{
DbSet<Parent> Root {get; set;}
DbSet<Grandchild> Grandchildren {get; set;}
}
Please, notice that the context doesn't expose a DbSet for the class Children
. 请注意,上下文没有为
Children
类公开DbSet。
So, what's the correct way to delete everything under a Parent
? 那么,删除
Parent
下所有内容的正确方法是什么?
First you need to make sure, Entity Framework has a Foreign Key . 首先,您需要确保Entity Framework 具有外键 。
Then you should be able to cascade delete : 然后您应该能够级联删除 :
Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database.
当在数据库中删除父记录时,级联删除会自动删除从属记录或将ForeignKey列设置为null。
Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.
默认情况下,实体框架中对所有类型的关系(例如一对一,一对多和多对多)启用级联删除。
So the following code should remove every children 因此,以下代码应删除所有子级
var parent = _dbContext.Single(predicate)
_dbContext.Remove(parent);
_dbContext.SaveChanges();
I guess it will be enough to remove DbSet<> declarations you dont need and then migrate the database. 我想这足以删除您不需要的DbSet <>声明,然后迁移数据库。 PowerShell:
电源外壳:
dotnet ef migrations add [name]
dotnet ef database update
Edit: above applies if you used code-first approach. 编辑: 如果您使用代码优先方法,则上述适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.