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 
}

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....