Executing the setDeleted loop causes changes to the entities which are then reflected in the saveChanges

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?

Answer №1

This scenario demonstrates a common issue of altering an array while looping through it. The problem arises when we remove elements like this:

    o.items.forEach(oi => {
      oi.entityAspect.setDeleted();
    });

...each time we call setDeleted, it eliminates the child entity from the parent items collection, which is the array being iterated over. Consequently, the next iteration skips the removed entity, resulting in only about half of the entities actually being marked for deletion.

The telltale signs of this issue include a SaveBundle containing a combination of deleted and modified entities, along with a potential foreign key violation if the parent entity is being deleted without removing all its children.

An easy fix is to duplicate the array before iterating through it, for example, using slice:

    o.items.slice().forEach(oi => {
      oi.entityAspect.setDeleted();
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover a method to deselect a checkbox within a separate component in angular15

I am currently dealing with Angular15 and I find myself stuck on an issue related to checkbox selection change. Situation: As per the requirements, I have a menu bar and a Checkbox. The Checkbox is generated from a reusable component which is used in the ...

What is the best approach to retrieve all user information using React with TypeScript and the Redux Toolkit?

I'm currently using React with TypeScript and Redux Toolkit, but I've hit a roadblock trying to retrieve user information. Below is my userSlice.ts file: export const userSlice = createSlice({ name: "user", initialState: { user: null, } ...

Is it possible to retrieve cached data from React Query / Tan Stack Query outside of the React tree?

Currently, I am in the process of developing an error handler for our mobile app that will send user data to the server when unexpected errors occur. Previously, I was able to easily retrieve user information from a global state. However, after removing t ...

Add a React component to the information window of Google Maps

I have successfully integrated multiple markers on a Google Map. Now, I am looking to add specific content for each marker. While coding everything in strings works fine, I encountered an issue when trying to load React elements inside those strings. For ...

Unlocking the Potential of ListView: A Guide to Maximizing Value

I have some code to work with: <head> <title><%=txtTitle.Text</title> </head> <asp:HiddenField ID="txtTitle" runat="server" /> <asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita"> <Item ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Optimal method for recording logs to a .txt file from a command line application

What is the most effective method for logging data to a .txt file from a C# console program in .NET 2.2? My program has a looping structure that generates different output based on user input, so I need an efficient way to record this data. I understand t ...

Uploading and accessing Excel content in Mvc5

I'm encountering an issue with saving and reading from an xls file using MVC5. The problem I am facing is that the saved file is not readable by Excel. Can someone provide assistance or guidance on this matter? It seems like I might be overlooking som ...

Tips for tuning a MatTable in angular without using a filterPredicate

I'm facing a challenge with my MatTable component where I need to filter the data using previously stored values from user input. While I can verify that the values match the data, I'm unsure of how to apply filtering without relying on the filte ...

Establish a reactive form upon data completion (asynchronously) in Angular version 5

I've been encountering an issue with updating form values post fetching data from an API. I attempted to utilize the *ngIf technique, but unfortunately, the form remains invisible even though it is properly set. Although I cannot provide the entire p ...

What is the process of converting a byte array into a blob using JavaScript specifically for Angular?

When I receive an excel file from the backend as a byte array, my goal is to convert it into a blob and then save it as a file. Below is the code snippet that demonstrates how I achieve this: this.getFile().subscribe((response) => { const byteArra ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

Transform a linear MongoDB record into a structured C# class

When integrating an API into an existing database that has a flat MongoDB document schema, I encountered a challenge. The document structure lacks nested objects, making it difficult to deserialize a group of fields into a child object. I have considered u ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

What is the reason for the manual update of a view when copying an object's attributes into another object, as opposed to using Object.assign()?

In my application, I have a parent component called 'EmployeeComponent' that is responsible for displaying a list of employees. Additionally, there is a child component named 'EmployeeDetailComponent' which displays the details of the s ...

Template specific requirements in Angular

When I have a child component app-page-header, here's what I want to achieve: If the value of headerOptions.headerTitle is not 'Idle Disposition', then set [titleData] to equal 'headerOptions.headerTitle'. However, if headerOptions ...

I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

const myList = document.createElement("div"); myList.setAttribute('id', 'name'); const list1 = document.createElement("ul"); const item1 = document.createElement("li"); let value1 = document.createTe ...

Can you explain the distinction between Type.IsSubclassOf and TypeInfo.IsSubclassOf?

Recently, I discovered that there are two techniques available to determine if a class is derived from another class: The original method, dating back to the .NET framework 1.1 : Type.IsSubclassOf(Type) A more modern approach introduced in the .NET frame ...

What strategies can I use to address the problem of 'unable to resolve import in '@/...'" in vitest?

I encountered an error related to a file path defined in the "vite.config.ts" file. Can you assist me with this issue? Error Log Error Message: FAIL tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...