Open Closed

Delete multiple Child entities when deleting parent #9722

dougmorato created

We have just started developing a new product using ASPNetZero 9.1 Angular version. But I have doubts regarding the CRUD operation of entities with multiple parent-child relations. We have a “Parent” entity that contains a collection of “Child” entities. The “Child” table has the foreign key of parent ID. Now When deleting one “Parent”, I want to delete all the associated children. I don’t want to enable cascade delete at the DB level. To achieve this first I have deleted all the children and removed the parent. Please the pseudo-code below

Is it the optimal way to achieve this requirement? Actually, I am concern about the performance impact of calling child repository within the loop, there many huge numbers of children.

`[AbpAuthorize(AppPermissions.PagesParentDelete)] public async Task Delete(EntityDto input) { var parent = await parentRepository.GetAllIncluding(v => v.Children) .FirstOrDefaultAsync(v => v.Id == (int)input.Id); foreach (var child in parent.Children) { await childRepository.DeleteAsync(child.Id); } await _parentRepository.DeleteAsync(input.Id); }`

2 Answer(s)
  • 0
    ismcagdas created
    Support Team


    You can delete BatchDeleteAsync method to delete the child entities. You don't have to retrieve the entities before deleting them. You can just call;

    await childRepository.BatchDeleteAsync(e=> e.parentId == (int)input.Id);

  • 0
    dougmorato created

    Thanks a lot.