简体   繁体   English

如何优化此EF查询并实现分页?

[英]How do I optimize this EF query and implement paging?

I have about 14,000 rows of data. 我有大约14,000行数据。 If use the following EF query, its a long time to load because I suspect it is loading all 14,000 rows and only then is any additional filtering done. 如果使用以下EF查询,则加载时间很长,因为我怀疑它正在加载所有14,000行,然后才进行任何其他过滤。 This is my Select method in my repository. 这是我的存储库中的Select方法。

Public Function SelectAll() As IEnumerable(Of be_Posts) Implements IPostRepository.SelectAll
       Dim posts As IEnumerable(Of be_Posts)
       Using db As Ctx = New Ctx
           posts = db.be_Posts.OrderByDescending(Function(x) x.DateCreated).ToList
           Return posts
       End Using

And Controller: 和控制器:

Function Index(page As Integer?) As ActionResult
        Dim PageSize = System.Web.Configuration.WebConfigurationManager.AppSettings("PageSize")
        Dim pageNumber As Integer = If(page, 1)
        Dim posts = _repo.SelectAll()
        Return View(posts.ToPagedList(pageNumber, PageSize))
    End Function

Helper in View: 视图中的助手:

@Html.PagedListPager((Model), Function(page) Url.Action("Index", New With { _
       .page = page _
        }), PagedListRenderOptions.ClassicPlusFirstAndLast)

Now If add in a take clause, for example .Take(500) then things are dramatically faster. 现在,如果添加一个take子句,例如.Take(500)那么事情将会大大加快。 How can I make this query faster and still work will all the records? 我如何才能使此查询更快,并且所有记录仍然可以使用? I am also using Troy Goode's PagedList extension to get paging functionality. 我还使用Troy Goode的PagedList扩展来获取分页功能。 Everything is fine as long as i get just a few hundred records. 只要我得到几百条记录,一切都很好。 So what to do? 那么该怎么办? Most if not all examples of paging that I can find that use Troy's library involve all the code directly in the controller. 我发现使用Troy库的大多数(即使不是全部)分页示例都直接在控制器中包含所有代码。

Calling ToList executes the query and, as you say, it's getting every record. 调用ToList执行查询,正如您所说,它将获取每条记录。 Paging is done using Skip and Take , eg 分页是使用Skip and Take ,例如

Dim page = list.Skip(pageSize * (pageNumber - 1)).Take(pageSize)

The source list can be the table itself or the result of a Where or OrderBy call or whatever. 源列表可以是表本身,也可以是WhereOrderBy调用或任何结果的结果。 Just make sure that ToList or, preferably, ToArray is called last. 只要确保最后调用ToListToArray (最好是ToArray )即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM