There is a book management system web application based on ASP.NET MVC3. When click the book index page, data query is very slow and user has to wait for several seconds for response. The code of Action Index in BookController below:
public ViewResult Index(string sortOrder, int? page)
{
ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "desc" : "";
ViewBag.CurrentSort = sortOrder;
BookModel books = from b in db.Books select b; // db = new BookContext();
switch (sortOrder) {
case "desc":
books = books.OrderByDescending(b => b.Name);
break;
default:
books = books.OrderBy(b => b.Name);
break;
}
int pageSize = 15;
int pageNumber = (page ?? 1);
return View(books.ToPagedList(pageNumber, pageSize));
}
In my opinion, the main reason of slow is that server does not response to client until all data are ready. This process takes much time.
I do not know how to solve this problem, is there any method to improve data query performance in this case? Thank you!
update: backend database is SQL Server Compact Edition 4.0
UPDATE
I update my logic code below, orderby is used before skip and take statements. Everything goes well. Thank you all for help.
books = (from b in db.Books
orderby b.Name descending
select b)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
Bookenities or add a database index on theNamecolumn in theBooktable. Indices also seeds up ORDER BY queries. And it's also strange that it takes long time, how many lines do you have in theBookstable? Maybe the slowness is caused some other code. Have you done any profiling?ToPagedListapplies pagination at database server or in memory?