My goal is to delete a hierarchy of objects:
Customer->Orders->OrderItems->OrderItemOptions
I attempted to set up a nested loop to perform the operations in the correct order - deleting child records before deleting parent records as required by the database.
Here is the loop I created:
deleteCustomer(customer: Customer): Promise<void> {
return this.getCustomerOrderHistory(customer.id).then(orders => {
orders.forEach(o => {
o.items.forEach(oi => {
oi.options.forEach(opt => opt.entityAspect.setDeleted());
oi.entityAspect.setDeleted();
});
o.entityAspect.setDeleted();
});
customer.entityAspect.setDeleted();
});
}
The issue arises when setting the parent object at each level to setDeleted(). This action results in duplicate entity records being marked as "modified" in the EntityManager's changes buffer. Subsequently, when saveChanges is called, the ASP.NET/EF backend throws an exception because the UPDATE statements corresponding to those modified records are executed after the DELETEs, causing the UPDATEs to fail with a FK not found exception.
What am I overlooking in this process?