Linq嵌套group by来操纵身份数据

时间:2014-12-15 09:41:59

标签: c# linq

您好我一直试图将一个数据结构的形状改为另一个数天,但没有运气。

原始数据结构如下。

public class Role : IdentityRole
{
    public string Name { get; set; }
    public virtual List<PermissionInRole> PermissionsInRole { get; set; }
}

public class PermissionInRole
{
    public Guid Id { get; set; }
    public virtual Permission Permission { get; set; }
    public virtual Feature Feature { get; set; }
}

public class Permission
{
    public Guid Id { get; set; }

    public string Description { get; set; }
}

public class Feature
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual Application Application { get; set; }
}

public class Application
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual List<Feature> Features { get; set; }
}

我想用Linq将它改成这种形状。

public class ApplicationApiModel
{
    public string Name { get; set; }

    public ICollection<FeaturesApiModel> Features { get; set; }
}

public class FeaturesApiModel
{
    public string Name { get; set; }

    public IEnumerable<PermissionsApiModel> Permissions { get; set; } 
}

public class PermissionsApiModel
{
    public string PermissionName { get; set; }

    public IEnumerable<Role> Role { get; set; }
}

public class Role
{
    public string Name { get; set; }
}

我希望有一个包含功能集合的应用程序集合,其中包含一组权限,其中包含具有父权限的角色集合。

我确信这可以通过linq完成,但是我没有得到任何帮助会很棒。

1 个答案:

答案 0 :(得分:1)

经过多次尝试后,我最终得到了以下工作代码

            var query = from role in roles
                    group role by role.PermissionsInRole
                        into g
                        select new
                        {
                            PinR = g.Key,
                            role = g.ToList()
                        };

        var transferList = (from w in query
            from pr in w.PinR
            select new
            {
                Feature = pr.Feature, Permission = pr.Permission, TransferRole = w.role.Single()
            })
            .ToList()
            .GroupBy(o => o.Feature, (key, o) =>
            new FeaturesApiModel
            {
                Name = key.Name,
                Permissions = o.GroupBy(transferObject => transferObject.Permission, (subKey,transferObject) =>
                    new PermissionsApiModel
                    {
                        PermissionName = subKey.Description,
                        Role = transferObject.Select(flatTransferObject => new RoleAPIModel {Name = flatTransferObject.TransferRole.Name})
                    }
                )
            });