2017-01-10 44 views
-1

我正在使用PagedList.MVC nuget, ,每次点击下一个按钮需要将近10秒。 我已经看到PagedList中有大约35万条结果,每次我点击下一个按钮时,它都会再次查看所有结果。我应该如何解决这个问题?如何解决在.net mvc中分页时的性能问题?

这是代码。

public ActionResult Index(int? page) 
     { 
      List<Item> items; 
      using (var db = new DBDevEntities()) 
      { 
       items= db.items.ToList(); 
      } 

      var pageNumber = page ?? 1; 

      return View(items.ToPagedList(pageNumber, 25)); 
     } 
+1

你做分页 –

+0

你每次加载整个列表你的页面缓存之前,不要使用'名单'和'.ToList()'(即加载所有记录到内存'items'的值放到你的控制器的属性中(或者更好的是实现分页服务器端) –

+0

@stephenmuecke你应该使用它吗? –

回答

4

db.items.ToList();加载所有350000个记录到内存中,然后你在代码过滤上。你需要使用.Skip().Take()做分页数据库端。

编辑:显然PagedList.MVC照顾这个,你只需要保持它在IQueryable而不是调用.ToList()。从https://github.com/TroyGoode/PagedList

public class ProductController : Controller 
{ 
    public object Index(int? page) 
    { 
     var products = MyProductDataSource.FindAllProducts(); //returns IQueryable<Product> representing an unknown number of products. a thousand maybe? 

     var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1) 
     var onePageOfProducts = products.ToPagedList(pageNumber, 25); // will only contain 25 products max because of the pageSize 

     ViewBag.OnePageOfProducts = onePageOfProducts; 
     return View(); 
    } 
} 
+0

'.ToPagedList()'使用'.Skip()'和'.Take()':) –

+0

你应该小心,在运行ToPagedList()之前不要处理DbContext。 – juunas

+0

所以,如果我在数据库第一模式使用实体框架。我应该如何获得IQueryble ?我试过var items = db.items;然后返回View(items.ToPagedList(pageNumber,25));有一个错误只有LINQ to Entities中的排序输入支持'Skip'方法。方法'OrderBy'必须在方法'Skip'之前调用。 @保罗·雅培 – Wilheim

相关问题