微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ASP.Net Identity 2.0中的不同用户类型

所以,我正在尝试在我的应用程序上实现不同类型的用户,首先,假设只有一种用户

public class ApplicationUser : IdentityUser
{
    // Other Properties
    public int TeacherID { get; set; }

    [ForeignKey("TeacherID ")]
    public virtual Teacher Teacher { get; set; }
}

public class Teacher
{
    [Key]
    public int TeacherID { get; set; }
    public int UserID { get; set; }
    // Other properties

    [ForeignKey("UserID")]
    public virtual ApplicationUser User { get; set; }
}

这两个实体之间存在一对一的关系,但是如果有多种类型的用户呢?我不能在User实体上拥有那个ForeignKey,我想我的方向是错误的.

我虽然为此使用角色,所以每个角色都有管理员,教师,学生和不同类型的角色,但如果我想为每种角色存储额外的属性会怎样?

public class IdentityUserRole<TKey>
{
    public IdentityUserRole();

    // Resumen:
    //     RoleId for the role
    public virtual TKey RoleId { get; set; }
    //
    // Resumen:
    //     UserId for the user that is in the role
    public virtual TKey UserId { get; set; }
}

我的意思是,我可以扩展IdentityUserRole类并添加更多属性,但是如何为每种角色添加属性

解决方法

为此目的使用角色当然是有意义的,但它确实意味着您可以分配多个角色.所以用户可以是教师和学生,但这可能发生.

如果要为角色类添加额外的属性,则以与为用户相同的方式完成.像这样创建自己的角色版本:

public class ApplicationRole : IdentityRole
{
    public string bool CanJuggle { get; set; }
}

你需要一个RoleManager类来配合它:

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole> store)
        : base(store)
    { }

    //snip
}

不要忘记你的上下文需要改变:

public class YourContext : IdentityDbContext<ApplicationUser,ApplicationRole,string,IdentityUserLogin,IdentityUserRole,IdentityUserClaim>
{       
    //snip 
}

认为涵盖了所有相关部分.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐