In this series, we will explore the Social Recipes sample application. This is a simple application that is intended to show some of the common inefficient queries that can be generated using Entity Framework (EF) Code First. The application is built using ASP.NET MVC4 and Entity Framework 5.
The application is site that allows users to post, rate, and review recipes, create and join groups, and share recipes with those groups. For more information on the domain, refer to Part 1 - Eager Loading.
Loading too much data
In the last post, we explored using LINQ projections to generate SQL queries that only retrieve the data that is needed to display a particular page. Using LINQ projections, we were able to improve performance substantially. There is, however, one more problem to solve with this Groups page.
We know the Groups page now performs well when we have 100 Groups in the database. You know what’s cooler than 100 Groups? Let’s see what happens when we have 1,000 groups on the page.
The page is taking 800ms to render. The problem is that we are trying to display ALL the Groups at once. Really, this is a NOT great idea. As our user base grows, the website will get slower and slower.
Paging
Luckily, we can implement a strategy called paging using the Skip and Take extensions methods.
First, let’s change the controller action to add a page number parameter and use that parameter when we add the Skip and Take methods to our query.
public ActionResult Index(int pageNumber = 0) |
Next, we update the Groups page to have links to the Next and Previous pages. To keep the example simple, I won’t check to see if we should actually be showing the Previous and Next links.
<div> |
Now, we are back to rendering the Groups page in under 50ms. The nice thing is that no matter how many groups are in the database, the page will always take approximately the same amount of time to load.
When we look at the generated SQL, we see that it is using the TOP command to only load 25 rows at a time.
DECLARE @p__linq__0 DateTime2 = '2013-02-16T17:08:19' |
What’s Next?
Get the source Social Recipes on GitHub