Select a range with Entity Framework

独自空忆成欢 提交于 2019-12-18 13:23:17

问题


I have an issue trying to maximize the performance of our listview that has pages.

I want the entity framework to do a select statement, but only return a range of the result (range = the items of one page of the listview).

I have searched google but didn't find any results on this. I only found that I can do a .ToList().GetRange(start index, end index), but then all items would be loaded in memory, and that is what I would like to avoid...

Can someone tell me if this can be done? (I don't want to use a stored procedure or view or something like that because our listview has to be reusable...)

Thanks!


回答1:


You should be able to use .Take(x).ToList()

edit: sorry, try .Skip(startPosition).Take(numberOfItems).ToList()




回答2:


And if you are not using lazy loading be sure to use Query() before Load() when applying filters to avoid loading the whole collection before applying filters :

context.Entry(blog) 
    .Collection(b => b.Posts) 
    .Query() 
    .Skip(startPosition)
    .Take(numberOfItems)
    .Load()
    .ToList(); 

When using the Query method it is usually best to turn off lazy loading for the navigation property. This is because otherwise the entire collection may get loaded automatically by the lazy loading mechanism either before or after the filtered query has been executed.

For more details : http://msdn.microsoft.com/en-us/data/jj574232.aspx



来源:https://stackoverflow.com/questions/5879764/select-a-range-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!