concept book list query in category entity framework

appears as: The book list query, book list query
Entity Framework Core in Action

This is an excerpt from Manning's book Entity Framework Core in Action.

In section 13.2, I show that in EF Core 2.0, the loading of the Author’s names collection for a book causes a new database access for each book. The book list query that reads in 10 books has 1 + 10 trips to the database: one for the book information of all 10 books, and then a single database access for each book’s list of authors. This is known as the N + 1 query problem.

Section 12.1.2 showed that the book list query needs to have great performance, so this chapter is about performance-tuning that query. The query has already avoided nearly all the performance issues mentioned in chapter 12, so you must go beyond the normal changes to make any further improvements. This chapter takes you through a series of performance-tuning steps, starting with EF Core–focused approaches and then branching out to more-extreme changes to get the best performance possible.

The book list query implemented in chapter 2 is split into four separate query objects: MapBookToDto, OrderBooksBy, FilterBooksBy, and a generic paging method. That means each part is easy to understand and can be separately tested. Duplicating this query in Dapper requires you to sacrifice the elegance of query objects and move to a design that combines snippets of SQL to create the query. But sometimes that’s what you need to do to squeeze out the best performance. Figure 13.4 shows how the Dapper version of the book list query dynamically builds the SQL command.

Figure 13.4 The Dapper code consists of a series of string concatenations to produce the final SQL query. It’s not as elegant as the EF Core version, with its four query objects, but when you’re performance tuning, you often must accept some loss of “cleanness” from your original code to achieve the performance you need.

13_04.png

Listing 13.5 shows the method called BookListQuery that’ll execute the book list query by using the sort, filter, and paging options the user has requested. The listing also shows the BuildQueryString that does the string concatenations shown in figure 13.4. To save space, I’ve left out all the rest of the code for creating the SQL. You can find the full code on GitHub at http://mng.bz/z1gE.