问题
我想在我的 ASP.NET MVC 项目中实现动态授权,其中资源权限可以由系统管理员动态分配给用户和角色。我正在使用下表来管理权限。
这些表的模型是
- public class Resource
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { get; set; }
- public int? ParentResourceId { get; set; }
- public string Name { get; set; }
- public string DisplayName { get; set; }
- public int Order { get; set; }
- public Resource ParentResource { get; set; }
- public ICollection<Permission> Permissions { get; set; }
- }
- public class Permission
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { get; set; }
- public int ResourceId { get; set; }
- public string Name { get; set; }
- public string DisplayName { get; set; }
- public int Order { get; set; }
- public Resource Resource { get; set; }
- }
复制代码
我需要根据树视图等 UI 上的资源层次结构显示资源权限,以便管理员可以检查并向用户和角色分配权限。使用递归函数(如下所示),我可以创建一个资源层次结构(仅从资源表),但不能包含此层次结构的权限。
到目前为止我正在尝试的代码如下:
- public List<PermissionTreeDto> GetPermissions()
- {
- var permissions = _context.Resources
- .Where(r => r.OrganizationId == OrganizationId)
- .ToList();
- return permissions.Where(r => r.ParentResourceId == null)
- .OrderBy(r => r.Order)
- .Select(r => new PermissionTreeDto
- {
- id = 0,
- text = r.DisplayName,
- @checked = false,
- children = GetChildren(permissions, r.Id)
- }).ToList();
- }
- private List<PermissionTreeDto> GetChildren(List<Resource> permissions, int parentId)
- {
- return permissions.Where(r => r.ParentResourceId == parentId)
- .OrderBy(r => r.Order)
- .Select(r => new PermissionTreeDto
- {
- id = 0,
- text = r.DisplayName,
- @checked = false,
- children = GetChildren(permissions, r.Id)
- }).ToList();
- }
复制代码
我正在使用 gijgo 引导树视图:
我的模型设计也可能有问题。在这种情况下,请提出任何更好的方法来实现我正在寻找的东西。
回答
我以这种方式在获得许可的情况下管理层次结构 -
- public List<ResourceTreeDto> GetPermissions()
- {
- var resources = _context.Resources.Include(r=>r.Permissions)
- .Where(r => r.OrganizationId == OrganizationId)
- .ToList();
- return resources.Where(r => r.ParentResourceId == null)
- .OrderBy(r => r.Order)
- .Select(r => new ResourceTreeDto
- {
- id = 0,
- text = r.DisplayName,
- @checked = false,
- children = r.Permissions.OrderBy(p=>p.Order).Select(p => new ResourceTreeDto()
- {
- id = p.Id,
- text = p.DisplayName,
- @checked = false
- }).Union(GetChildren(resources, r.Id))
- }).ToList();
- }
- private IEnumerable<ResourceTreeDto> GetChildren(List<Resource> resources, int parentId)
- {
- return resources.Where(r => r.ParentResourceId == parentId)
- .OrderBy(r => r.Order)
- .Select(r => new ResourceTreeDto
- {
- id = 0,
- text = r.DisplayName,
- @checked = false,
- children = r.Permissions.OrderBy(p => p.Order).Select(p => new ResourceTreeDto()
- {
- id = p.Id,
- text = p.DisplayName,
- @checked = false
- }).Union(GetChildren(resources, r.Id))
- });
- }
复制代码
现在我得到了预期的输出 -
|