我们有一个简单的 LINQ-to-Entities 查询,它应该从特定页面返回特定数量的元素。请求的示例可以是:
var query = from r in records
orderby r.createdDate descending
select new MyObject()
{ ... };
//Parameters: pageId = 8, countPerPage = 10
List<MyObject> list = query.Skip(pageId * countPerPage).Take(countPerPage);
上面的例子在大多数情况下都很好用,但有时列表有超过 10 个元素。这似乎并不总是正确的,并且取决于数据库数据。例如,当我们请求页面 10 并将 countPerPage 传递为 10 时,我们将获得 10 个元素。但是当我们请求第 12 页并将 countPerPage 作为 10 传递时,我们将获得 11 个元素。然后,当我们请求第 21 页时,我们又得到了 10 个元素。
发生这种情况有什么可能的原因吗?
更新:当然,查询并不像示例中那样简单,并且包含子查询。
这是一个更完整的例子:
var elementsQuery = from m in entityContext.elements
where m.elementSearchText.Contains(filter)
orderby m.CreatedDate descending
select new DataContracts.ElementForWeb()
{
FirstName = m.FirstName,
LastName = m.LastName,
Photos = (from p in m.Photos select p.ID),
PlacesCount = m.Childs.Where(x => x.Place != null).Count() + ((m.MainChild != null)?1:0),
SubElements = (
from t in m.Childs
orderby t.CreatedDate descending
select new DataContracts.ChildForWeb()
{
CommentsCount = t.ChildComments.Count,
Photos = (from p in t.Photos select p.ID),
Comments = (from c in t.ChildComments
orderby c.CreatedDate descending
select new DataContracts.CommentForWeb()
{
CommentId = c.ID,
CommentText = c.CommentText,
CreatedByPhotoId = c.Account.UserPhoto,
CreatedDate = c.CreatedDate,
}).Take(5)
}).Take(5)
};
List<DataContracts.ElementForWeb> elements =
new List<DataContracts.ElementForWeb>(
elementsQuery
.Skip(pageId * countPerPage)
.Take(countPerPage));
UPDATE2:这是更有趣的测试。
for (var i = 0; i < 10; i++) {
Service.GetElementsForWebPaged(12, 10, "",
function (result) {
console.log("Elements returned: " + result.length);
},
function (error) {
});
}
结果“棒极了”!
Elements returned: 11
Elements returned: 11
Elements returned: 10
Elements returned: 11
Elements returned: 11
Elements returned: 10
Elements returned: 11
Elements returned: 10
Elements returned: 11
Elements returned: 11