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

c# data-structures entity-framework-core linq

Question

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; }
}
1
0
5/16/2018 7:58:15 AM

Accepted Answer

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.

0
5/18/2018 11:56:26 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow