IEnumerable vs IQueryable [英] IEnumerable vs IQueryable

查看:92
本文介绍了IEnumerable vs IQueryable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询:

topics.OrderBy(x => x.Replies.Any() ? x.Replies.OrderBy(y => y.PostedDate).Last().PostedDate : x.PostedDate);

它通过上次回复对主题集合进行排序,或者如果没有回复,则自己的发布日期。它工作很好,做得很好。但是,仅当主题类型为 IEnumerable< Topic> 时才起作用。如果我尝试使它IQueryable,我得到一个错误,说扩展方法Last()是未知的或这样的东西。

It sorts the topics collection by last reply, or if it has no reply then by its own post date. It works great and does its job well. However, it only works if topics is of type IEnumerable<Topic>. If I try to make it `IQueryable' I get an error saying the extension method Last() is unknown or something to that effect.

任何人知道为什么?由于某些原因在本查询中获取 x.Replies.Last(),而主题是IQueryable会引发此异常。

Anyone know why? For some reason getting x.Replies.Last() within this query while topics is IQueryable throws this exception.

我希望主题是IQueryable,因为我首先从数据库加载所有主题的主题,按最后一个答复排序。然后我就做主题的.Skip()和.Take()分页。然而,目前它正在将所有主题拉入内存,然后在内存集合中执行.Skip()和.Take()。这是不可接受的,因为添加到论坛的主题越多,加载网站就越长,特别是当数据库不在与网站相同的计算机上运行时。我需要数据库只返回分页行,而不是所有的行。我希望分页在数据库级别发生。

I would like topics to be IQueryable because I first load topics with all topics from the database, sorted by last reply. I then do .Skip() and .Take() on topics for paging. However, currently it is pulling ALL topics into memory and then doing the .Skip() and .Take() on the in-memory collection. This is unacceptable because the more topics that are added to the forum, the longer it takes to load the site, especially when the database is not running on the same computer as the website. I need the database to only return the paged rows, not all rows. I want the paging to occur at the database level.

任何想法?

PS - 我正在使用LINQ to Entities with Entity Framework 4.0

PS - I'm using LINQ to Entities with Entity Framework 4.0

推荐答案

你尝试过 topics.OrderBy(x => x .Replies.Any()?x.Replies.Max(y => y.PostedDate):x.PostedDate);

这篇关于IEnumerable vs IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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