Unnecessary volume returned

We have been using data luxuriously so far without keeping usage in mind. One fine example is the delete operation, which we can see in all the CRUD operations. If we take a look at the Person delete operation, we can see that the entire Person entity was returned from the context and it was used for the deletion. The following code retrieves the Person entity and uses the entity for delete operation:

    public async Task<IActionResult> DeleteConfirmed(int id)
{
var person =
await _context.People.SingleOrDefaultAsync(m => m.Id == id);

_context.People.Remove(person);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}

The pitfall for the preceding approach was, first a database call was made to retrieve the entire Person object, which is an overhead. After that, the required delete operation was performed using the Id of the person, which was available before the Person retrieval. The following screenshot is highlighted  with the discussed two queries:

We could simplify the approach by removing the person retrieval and creating a Person object using just the Id value, and updating the state of the entity as Deleted would instruct EF Core to perform a delete operation directly without retrieving the object from the data store. The following code reduces the query into one which performs delete operation alone:

    [HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
Person person = new Person() { Id = id };
_context.Entry(person).State = EntityState.Deleted;
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}

We can see that the preceding approach does not make any Person retrievals yet. Still, the delete operation was performed successfully, as shown in the following screenshot:

We have seen ways to avoid retrieving unnecessary data from the data store. In the next section, we will explore the N + 1 Select problem.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset