2014-10-20 46 views
6

所以,我想要实现不同类型的用户对我的应用程序,首先,让我们说,只有一个类型的用户:不同的用户类型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; } 
} 

有一到这两个实体之间有一种关系,但如果有多种类型的用户呢?我不能在用户实体上拥有这个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并添加更多的属性,但我怎么加属性,每个样的角色?

+0

您不能分别向每种角色添加属性。所有角色都将包含您在UserRole表中包含的所有属性,因为每个属性都将成为一列,但您可以将不同的职责分配给不同的角色。或者你可以使用基于声明的认证。查看这些视频以创建自定义角色。 http://stackoverflow.com/questions/25857806/extending-identityuserrole-in-identity-2-0/25857923#25857923 – DSR 2014-10-20 21:42:48

回答

4

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

如果您想为角色类添加额外的属性,它的操作方式与为用户完成的方式相同。像这样创建您自己的Role版本:

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 
} 

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

+0

我仍然对此感到困惑。我希望每种类型的用户都可以存储不同的属性,因此我可以拥有教师角色,协调员角色等,每个角色都有自己的任务。 – 2014-10-20 21:25:12