C# 实体框架分页 [英] C# Entity Framework Pagination

查看:28
本文介绍了C# 实体框架分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以获得复杂的 Linq 查询的行数和数百万条记录,而无需两次访问数据库或编写 2 个单独的查询??

Is there a way to get the row count of a complex Linq query and millions of records without hitting the db twice or writing 2 separate queries??

我可能有自己的建议.编写一个存储过程,但我擅长 MySQL 而不是 MSSQL.

I might have my own suggestion. Write a stored procedure, but I'm good with MySQL not MSSQL.

任何更好的建议都会很棒.另外,如果有人知道微软是否正在努力将此功能添加到实体框架中.

Any better suggestions would be great. Also, if anyone knows if Microsoft is working on adding this feature to the entity framework.

推荐答案

我建议使用 Take() 函数.这可用于指定从 linq 查询或列表中获取的记录数.例如

I'd suggest using the Take() function. This can be used to specify the number of records to take from a linq query or List. For example

List<customers> _customers = (from a in db.customers select a).ToList();
var _dataToWebPage = _customers.Take(50);

我在 MVC 应用程序中使用了类似的技术,我将 _customers 列表写入会话,然后在用户单击第 2、3 页等时使用此列表进行进一步的分页查询.这可以节省多次数据库点击.但是,如果您的列表非常大,那么将它也写入会话可能不是一个好主意.

I use a similar technique in an MVC app where I write the _customers list to the session and then use this list for further pagination queries when the user clicks on page 2, 3 etc. This saves multiple database hits. However if your list is very large then writing it too the session is probably not a good idea.

对于分页,您可以同时使用 Skip() 和 Take() 函数.例如获取数据的第 2 页:

For pagination you can use the Skip() and Take() function together. For example to get page 2 of the data :

var _dataToWebPage = _customers.Skip(50).Take(50);

这篇关于C# 实体框架分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆