针对ApplicationUser Roles导航属性的ASP MVC Build Throwing Warning?

时间:2016-08-01 19:35:44

标签: c# asp.net-mvc entity-framework linq asp.net-identity-2

我有以下ApplicationUser Model:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<ApplicationRole> Roles { get; set; }

    public bool HasRole(string _role)
    {
        return Roles.Any(r => r.Name == _role);
    }

    public bool HasPermission(string _permission)
    {
        return Roles.Any(r => r.Permissions
              .Any(p => p.Name == _permission));
    }
}

但是当我运行构建时,我收到以下警告消息:

ApplicationUser.Roles hides inherited member 
'IdentityUser<string, IdentityUserLogin,IdentityUserRole, IdentityUserClaim>.Roles. 
To make the current member override that implementation, add the overide keyword. Otherwise 
add the new keyword.

我的实施有问题还是应该以不同的方式完成?我添加了Roles导航属性,以便我可以实现HasRole和HasPermission方法。

我的Permission和ApplicationRole模型实现如下:

public class Permission
{
    public byte Id { get; set; }
    public string Name { get; set; }

    public virtual List<ApplicationRole> Roles { get; set; }
}


public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }

    public virtual ICollection<Permission> Permissions { get; set; }

    public bool IsPermissionInRole(string _permission)
    {
        return Permissions.Any(p => p.Name == _permission);
    }
}

1 个答案:

答案 0 :(得分:3)

我对 ASP.NET Identity 没有广泛的了解。但经过一番搜索,我可以给你粗略的回答。 IdentityUser 应该具有继承 IdentityUserRole 而不是 IdentityRole 的proeprty 角色。我认为这个模型与IdentityUsers和IdentityRoles有关。那么,你应该做的是创建继承 IdentityUserRole ApplicationUserRole 类:

public class ApplicationUserRole : IdentityUserRole
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

IdentityRole<string, ApplicationUserRole>继承您的ApplicationRole:

public class ApplicationRole 
    : IdentityRole<string, ApplicationUserRole>
{
}

然后在 ApplicationUser 类中使用此类。要使用ApplicationUserRole,您需要从IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>继承ApplicationUser而不是IdentityUser

public class ApplicationUser 
    : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    .............
}

最后,将 ApplicationUser HasPermission 方法更改为:

public bool HasPermission(string _permission)
{
    return Roles.Any(r => r.Role.IsPermissionInRole(_permission));
}

我再说一遍,这是粗略的答案。有关扩展身份模型的更多信息,请参阅this code project article