Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用EntityFramework的分页结果列表_C#_Entity Framework - Fatal编程技术网

C# 使用EntityFramework的分页结果列表

C# 使用EntityFramework的分页结果列表,c#,entity-framework,C#,Entity Framework,我有一个简单的SQL Server数据库,其中包含用户和社区的数据。任何用户都可以是任意数量社区的成员,因此我有3个表:用户、社区和地图,以及相应的POCO C#类。 我使用EntityFramework获取所有社区及其成员的字典: public Dictionary<Community, List<User>> GetData() { var communitiesAndUsers = from community in DbContext.Co

我有一个简单的SQL Server数据库,其中包含用户和社区的数据。任何用户都可以是任意数量社区的成员,因此我有3个表:
用户
社区
地图
,以及相应的POCO C#类。 我使用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;
}
公共字典GetData() { var社区和用户= 来自DbContext.Communities中的社区 来自DbContext.CommunityUserMap.Where中的映射(c=>c.Community==Community) 选择新建{Community=Community,User=map.User}; var result=newdictionary(); foreach(communities和users.ToList().GroupBy(x=>x.Community.Id)中的var communityGroup) { var community=communityGroup.First().community; var users=communityGroup.Select(g=>g.User.ToList(); 结果。添加(社区、用户); } 返回结果; } 现在我需要在此方法中支持分页:

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

我需要使用1个SQL查询来完成这项工作。我需要如何修改我的方法来支持它?

使用
跳过
获取
来实现分页。您还需要定义排序条件(
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

由于在应用
Skip
Take
之前未枚举
communities和users
,这将导致一个SQL查询(查询将在
ToList
上执行)。

但这将生成一个长度为
communities perpage
的对列表。因此,
结果
字典可能包含少于
communitiesPerPage
的记录,因为映射可能包含重复的communityid。我需要
结果
字典精确地包含
communities perpage
键。对,我刚刚更改了查询,在
跳过
获取
之前应用
GroupBy
,这应该会产生预期的结果。