如果对象为空,则禁止检查条件

时间:2018-07-10 13:07:24

标签: c# asp.net linq

简而言之: 用户可以拥有自己的权限。也可以将用户分配给包含权限的组。现在,我要检查用户是否具有权限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.Groupnull,则我得到argument null exception。我尝试过这样的事情:

user.Group?.GroupActionPermissions.Any(z => z.PermissionActionId == a.Id)

但是我遇到了错误:

Operator '||' cannot be applied to operands of type 'bool' and 'bool?'

我在那里可以做什么?

1 个答案:

答案 0 :(得分:1)

所有null-conditional operator都向您购买的是,它返回了null,而不是尝试访问null引用上的属性并引发异常。

所以您最终会遇到这样的事情:

IsSelected = false || null;

如果Groupnull,则需要提供默认值:

// 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))