简而言之:
用户可以拥有自己的权限。也可以将用户分配给包含权限的组。现在,我要检查用户是否具有权限x
,或他所在的组是否具有该权限。用户不能在任何组中。
viewModel.PermissionControllers = permissionControllers.Select(x => new PermissionControlerViewModel
{
Id = x.Id,
Name = x.ControllerName,
Description = x.Desciption,
Actions = x.PermissionActions.Select(a => new PermissionAction
{
Id = a.Id,
Name = a.Name,
Description = a.Description
IsSelected = user.ActionPermissions.Any(p => p.PermissionActionId == a.Id) || user.Group.GroupActionPermissions.Any(z => z.PermissionActionId == a.Id),
}).ToList()
}).ToList();
如果user.ActionPermissions.Any(p => p.PermissionActionId == a.Id)
返回false
,而user.Group
为null
,则我得到argument null exception
。我尝试过这样的事情:
user.Group?.GroupActionPermissions.Any(z => z.PermissionActionId == a.Id)
但是我遇到了错误:
Operator '||' cannot be applied to operands of type 'bool' and 'bool?'
我在那里可以做什么?
答案 0 :(得分:1)
所有null-conditional operator都向您购买的是,它返回了null
,而不是尝试访问null
引用上的属性并引发异常。
所以您最终会遇到这样的事情:
IsSelected = false || null;
如果Group
为null
,则需要提供默认值:
// provide a value to use if the first result is null, using a null coalescer
IsSelected = user.ActionPermissions.Any(p => p.PermissionActionId == a.Id)
|| (user.Group?.GroupActionPermissions.Any(z => z.PermissionActionId == a.Id) ?? false)
// if it's supported in your situation, you may be able to use HasValue
IsSelected = user.ActionPermissions.Any(p => p.PermissionActionId == a.Id)
|| (user.Group.HasValue && user.Group.GroupActionPermissions.Any(z => z.PermissionActionId == a.Id))