简体   繁体   English

使用EntityFramework的分页结果列表

[英]Paginated list of results using EntityFramework

I have a simple SQL Server DB containing data for Users and Communities. 我有一个简单的SQL Server数据库,其中包含用户和社区的数据。 Any user can be member of any number of communities, so I have 3 tables: Users , Communities and Map , and corresponding POCO C# classes. 任何用户都可以是任意数量的社区的成员,因此我有3个表: UsersCommunitiesMap以及相应的POCO C#类。 I use EntityFramework to get the dictionary of all communities and their memebers: 我使用EntityFramework获取所有社区及其成员的字典:

public Dictionary<Community, List<User>> GetData()
{
    var communitiesAndUsers =
        from community in DbContext.Communities
        from map in DbContext.CommunityUserMap.Where(c => c.Community == community )
        select new { Community = community, User = map.User };


    var result = new Dictionary<Community, List<User>>();
    foreach (var communityGroup in communitiesAndUsers.ToList().GroupBy(x => x.Community.Id))
    {
        var community = communityGroup.First().Community;
        var users = communityGroup.Select(g => g.User).ToList();
        result.Add(community, users);
    }

    return result;
}

Now I need to support pagination in this method: 现在,我需要以这种方法支持分页:

public Dictionary<Community, List<User>> GetData(int page, int communitiesPerPage)

And I have a requirement to do it using 1 SQL query. 我需要使用1个SQL查询来执行此操作。 How do I need to modify my method to support that? 我需要如何修改我的方法以支持该方法?

Use Skip and Take to implement the paging. 使用“ SkipTake来实现分页。 You will also need to define sort criteria ( Orderby ) to get consistent results. 您还需要定义排序标准( Orderby )以获得一致的结果。

var pagedCommunityGroups = communitiesAndUsers
    .GroupBy(cau => cau.Community.Id)
    .OrderBy(grp => grp.Key)
    .Skip(page * communitiesPerPage) // assume first page has number 0
    .Take(communitiesPerPage)
    .ToList();                       // execute query

Because communitiesAndUsers has not been enumerated before you apply Skip and Take , this will result in a single SQL query (query will be executed on ToList ). 因为在应用Skip and Take之前尚未枚举communitiesAndUsers ,这将导致单个SQL查询(查询将在ToList上执行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM