var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
Comments.userID, Comments.comment, Comments.date
});
这会返回所有关联的记录,我最好如何选择记录#10到#20,这样我才不会加载任何冗余数据?
答案 0 :(得分:4)
怎么样:
var q = (
from Comments in db.tblBlogComments
where Comments.blogID == this.ID
orderby Comments.date descending
select new { Comments.userID, Comments.comment, Comments.date }).Skip(10).Take(10);
答案 1 :(得分:2)
您可以在结果集上使用.Skip()
和.Take()
方法。例如:
var q = (from Comments in db.tblBlogComments where Comments.blogID == this.ID orderby Comments.date descending select new {
Comments.userID, Comments.comment, Comments.date
});
然后使用:
int pageSize = 10;
int page = 3;
var currentPage = q.Skip((currentPage - 1) * pageSize).Take(pageSize);
然后
foreach(var item in currentPage)
{
...
}
由于Linq使用延迟执行,将在foreach循环期间创建并执行实际查询。所以SQL查询只返回当前页面的记录。
答案 2 :(得分:0)
int start = 10;
int end = 20;
var q = (from Comments in db.tblBlogComments
where Comments.blogID == this.ID
orderby Comments.date descending
select new {
Comments.userID,
Comments.comment,
Comments.date
}).Skip(start).Take(end - start);
我不确定Skip
是否转换为在数据库中执行的SQL,因此效率可能不高。