Vivek Nuna
Vivek Nuna

Reputation: 1

How to delete a tree in C# Entity Framework Core?

I have a Category class, which has List<Category>. So it makes a tree kind of structure like Category then multiple subcategories then again multiple subcategories under it and so on.

I want to delete this whole tree, I have implemented the below method, but it's not working as expected.

public async Task DeleteCategoryById(int Id)
{
    CategoryDto category = new CategoryDto();
    var details = _categoryRepository.GetAll().Where(x => x.Id == Id);

if (details == null)
{
 return;  
}
var children = (_categoryRepository.GetAll().Where(x => x.ParentId == Id));
int childCount = children.Count();

if (childCount != 0 )
{
    category.Category = ObjectMapper.Map<List<CategoryDto>>(children);
}

if (category.Category == null)
{
   await _categoryRepository.DeleteAsync(x => x.Id == Id);
}
else
{
    for (var i = 0; i < childCount; i++)
    {
      await  DeleteCategoryById(category.Category[i].Id);
    }
}
}

public class Category
{
    public int Id { get; set; }
    public string CategoryName { get; set; }
    public bool IsLast { get; set; } = true;
    public int ParentId { get; set; }
    public List<Category> Category { get; set; }
}

Upvotes: 0

Views: 1200

Answers (2)

Vivek Nuna
Vivek Nuna

Reputation: 1

Thanks, @Ivan Stoev for your suggestions, it worked for me.

Moving await _categoryRepository.DeleteAsync(x => x.Id == Id); to the end of the method (unconditionally after deleting children). I was deleting recursively just the leaf children.

Upvotes: 0

Anderson Martins
Anderson Martins

Reputation: 126

1st Option: In your context class you should enable on delete cascade behavior:

Example:

protected override void OnModelCreating(Modelbuilder modelBuilder)
{
    modelBuilder.Entity<Category>()
   .HasMany(c => c.Category)
   .WithOne(e => e.Category).
   .OnDelete(DeleteBehavior.Cascade );
}

OR

2nd Option: Delete the childrem first, and then delete the main category

Upvotes: 1

Related Questions