实体框架数据库选择使用Skip和Take获取整个表格

时间:2014-11-13 05:20:13

标签: entity-framework

我有以下EF代码

Func<CxForumArticle, bool> whereClause = a => a.CreatedBy == authorId;

IEnumerable<CxForumArticle> articlesCol = ctx.Articles
              .Where(whereClause)
              .Where(a => a.PublishingStatus == EnPublishStatus.PUBLISHED)
              .OrderByDescending(a => a.ModifiedOn).Skip(offset).Take(pageSize);

它生成以下SQL

SELECT 
    [Extent1].[ArticleId] AS [ArticleId], 
    [Extent1].[Alias] AS [Alias], 
    [Extent1].[MigratedId] AS [MigratedId], 
    [Extent1].[Title] AS [Title], 
    [Extent1].[Teaser] AS [Teaser], 
    [Extent1].[ClobId] AS [ClobId], 
    [Extent1].[UnifiedContentId] AS [UnifiedContentId], 
    [Extent1].[EditorComments] AS [EditorComments], 
    [Extent1].[CreatedOn] AS [CreatedOn], 
    [Extent1].[CreatedBy] AS [CreatedBy], 
    [Extent1].[ModifiedOn] AS [ModifiedOn], 
    [Extent1].[ModifiedBy] AS [ModifiedBy], 
    [Extent1].[PublishingStatus] AS [PublishingStatus]
    FROM [dbo].[ForumArticle] AS [Extent1]

如您所见,此SQL中没有排序和分页。所以EF命令和页面数据在内存中。 这似乎不是一件好事。

我读了一篇文章,声称我必须在OrderBy子句中使用表达式。我做到了

Func<CxForumArticle, bool> whereClause = a => a.CreatedBy == authorId;

Expression<Func<CxForumArticle, DateTime>> orderByFunc = a => a.ModifiedOn; 

IEnumerable<CxForumArticle> articlesCol = ctx.Articles
              .Where(whereClause)
              .Where(a => a.PublishingStatus == EnPublishStatus.PUBLISHED)
              .OrderByDescending(orderByFunc.Compile()).Skip(offset).Take(pageSize)
              ;

但我得到了同样的结果。任何想法如何强制EF在数据库中对数据进行排序和分页?

1 个答案:

答案 0 :(得分:0)

我知道这很老了,但实际上你需要让whereClause也使用表达式。实体框架只知道如何将表达式转换为SQL。如果使用委托而不是表达式,它将查询整个表,然后使用LINQ to Objects进行过滤。