c# - 使用 LINQ 将分层结果集转换为自定义对象

标签 c# entity-framework linq hierarchical-data

我有一个分层结果集,如下所示:

enter image description here

然后我有一个这样的自定义对象:

public class AuthorizedEntity
{
    public Departments Department { get; set; }

    public string Username { get; set; }

    public List<AuthController> Controllers = new List<AuthController>();        
}

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

    public List<AuthAction> Actions = new List<AuthAction>();
}

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

    public List<string> Methods = new List<string>();
}

是否可以将以下数据转换为相应的对象?在本例中,用户名是 justinfarrugia,Controller = StocktakeController,Actions = 权限,方法 = 编辑权限和设置权限,操作 = StockEvaluation,方法 = 更新测量。

我正在寻找最有效的解决方案。

我已经尝试过,但它没有让我达到预期的结果:

ObjectResult<SP_GetPrivilegesByUsername_Result> lstAuthorizedUsersRaw = dbsp.SP_GetPrivilegesByUsername(inUsername.Trim());
        lstAuthorizedUsersRaw.GroupBy(p => p.Cntrollers_Name).ToList().ForEach(r =>
        {
            authEntity.Controllers.Add(new AuthController()
            {
                Name = r.Key,
                Actions = new List<AuthAction>() {
                                                    new AuthAction() {
                                                                        Name = r.ToList().Select(q => q.HMVAct_Name).FirstOrDefault(),
                                                                        Methods = r.ToList().Select(w => w.HMVMethd_Name).ToList()

                                                                     }
                                                 }
            });
        });

谢谢

最佳答案

您错过了第二次分组 - 当您从 Controller 组中选择操作时:

var lstAuthorizedUsersRaw = dbsp.SP_GetPrivilegesByUsername(inUsername.Trim());

authEntity.Controllers = lstAuthorizedUsersRaw
      .GroupBy(p => p.Cntrollers_Name)
      .Select(controllerGroup => new AuthController {
         Name = controllerGroup.Key,
         Actions = controllerGroup
                    .GroupBy(p => p.HMVAct_Name) // here
                    .Select(actionGroup => new AuthAction {
                        Name = actionGroup.Key,
                        Methods = actionGroup.Select(pu => p.HMVMethd_Name).ToList()
                    }).ToList()
      }).ToList();

关于c# - 使用 LINQ 将分层结果集转换为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197457/

相关文章:

asp.net - Entity Framework 4(使用EDMX),如何将字段添加到数据库实际上没有该字段的模型中

c# - 错误 : The object cannot be deleted because it was not found in the ObjectStateManager

c# - 如何使用 LINQ 加入、分组和选择?

c# - 在linq查询中循环遍历数组

c# - 忽略 TransactionScope 中的 SqlTransaction.Commit

c# - 从 DataGrid 的 DataGridTemplateColumn 获取复选框值

c# - 如何声明两个类以便将它们传递给同一个函数?

c# - 使用 ViewBag 的 Asp.net mvc 下拉列表

c# - EF 一对一主要关系错误

c# - 如何从多个 List<> 中获取所有元素?