如何使用 Linq to Sql 实现 SkipWhile 而不首先将整个列表加载到内存中?
我需要按发布日期降序对存储在数据库中的文章进行排序,然后获取文章后 Id == 100
的前 20 条记录。
这就是我想对 Linq 执行的操作:
IQueryable<Article> articles =
db.Articles
.OrderByDescending(a => a.PublicationDate)
.SkipWhile(a => a.Id != 100)
.Take(20);
但是,这会生成 NotSupportedException,因为 Linq to Sql 不支持 SkipWhile
(请参阅 此处)。
一种可能的解决方案是执行查询,然后使用 Linq to Object 应用 SkipWhile
:
IEnumerable<ArticleDescriptor> articles =
db.Articles
.OrderByDescending(a => a.PublicationDate)
.ToList()
.SkipWhile(a => a.Article.Id != 100)
.Take(20);
但这意味着我需要先将整个有序列表加载到内存中,然后在使用 的文章之后获取 20 篇文章ID == 100
。
有没有办法避免这种巨大的内存消耗?
更一般地说,在 SQL 中实现此目的的最佳方法是什么?
I need to order the articles stored in a database by descending publication date and then take the first 20 records after the article with Id == 100
.
This is what I would like to do with Linq:
IQueryable<Article> articles =
db.Articles
.OrderByDescending(a => a.PublicationDate)
.SkipWhile(a => a.Id != 100)
.Take(20);
However, this generates a NotSupportedException because SkipWhile
is not supported in Linq to Sql (see here).
A possible solution is to execute the query and then apply SkipWhile
using Linq to Object:
IEnumerable<ArticleDescriptor> articles =
db.Articles
.OrderByDescending(a => a.PublicationDate)
.ToList()
.SkipWhile(a => a.Article.Id != 100)
.Take(20);
But this means I need to load the whole ordered list into memory first and then take 20 articles after the one with Id == 100
.
Is there a way to avoid this huge memory consumption?
More in general, what is the best way to achieve this in SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如我从列名称中猜测的那样,如果
PublicationDate
没有更改,您可以在两个单独的查询中执行此操作:Article 的
和PublicationDate
Id == 100
类似于:
LINQ to SQL 甚至可能可以转换此内容:
但这对于 它。尝试一下看看。
If, as I'm guessing from the column name,
PublicationDate
doesn't change, you can do this in two separate queries:PublicationDate
of theArticle
withId == 100
Something like:
It might even be that LINQ to SQL can translate this:
but that may be too complex for it. Try it and see.
你可以这样尝试
You can try like this
不是只要添加一个where语句就可以解决吗?
Isnt the solution to just add a where statement?