More data than required

The About component we were creating consumes the Person entity, which contains a lot of information that is not necessary for the component, but still it is processed and returned to the View. We can see in the following code, the  AboutComponent  consumes the GetPersonByIdQuery and returns the entire Person entity to the View:

    public IViewComponentResult Invoke(int id)
{
var user = _repository.GetSingle(
new GetPersonByIdQuery(_context)
{
IncludeData = true,
Id = id
});
return View(user);
}

The preceding View component renders only the Name and Biography properties of the user entity. We can see them in the following view component code:

    <h2>About @Model.Name</h2>
<p>
@Model.Biography
</p>

The View component then consumes the data to render only the FirstName and Biography of the Person entity. It is obvious that we need to address this problem, as we are returning unnecessary data to the view.

We can visualize the rendered view from the following screenshot and see that it does not consume any other property from the user entity:

If we try to profile the data store call, we can see that there are a lot of columns included in the particular call, which consumes only two-column data:

We can now narrow down the data returned using projection and a View model, which restricts the data only to Name and Biography:

    public IViewComponentResult Invoke(int id)
{
var aboutViewModel = _context.People
.Where(item => item.Id.Equals(id))
.Select(item => new AboutViewModel
{
Name = item.FirstName,
Biography = item.Biography
}).SingleOrDefault();

return View(aboutViewModel);
}

Now, the profiler highlights the database call that contains only two columns required for the rendering of the database, thereby reducing the content that was retrieved from the database, as shown in the following screenshot:

This addresses our problem of returning too much data from the data store. In the next section, let's look into mismatched data types.

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

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