0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
SuperJMN
  • 13,110
  • 16
  • 86
  • 185

2 Answers2

0

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();
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • Thanks for the answer, but I think it's doesn't work for me. The Context I use is generated using a DB-First approach and I don't have control over it. Every related entity generates a navigation property and a foreign key. I'm getting errors like this: SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_XXX_XXX". The conflict occurred in database "XXXX_XXXX", table "ABC", column 'ID_XXXX'. The statement has been terminated. – SuperJMN Aug 08 '19 at 12:12
-1

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.

Alex Sherzhukov
  • 244
  • 2
  • 8