简体   繁体   中英

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)

class Parent 
{
    public ICollection<Child> Children { get; set; }
}

class Child 
{
    public ICollection<Grandchild> Grandchildren { get; set; }      
}

public class Grandchild 
{   
}

my DbContext is

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 .

So, what's the correct way to delete everything under a Parent ?

First you need to make sure, Entity Framework has a Foreign Key .

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.

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. PowerShell:

dotnet ef migrations add [name]
dotnet ef database update

Edit: above applies if you used code-first approach.

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