【发布时间】:2015-09-24 11:45:52
【问题描述】:
我已经扩展了 IdentityUserRole 如下
public class ApplicationUserRoles : IdentityUserRole<string>
{
[Key]
public string ApplicationId { get; set; }
public virtual AspNetApplications AspNetApplications { get; set; }
}
我的 AspNetApplications 类如下
public class AspNetApplications
{
[Key]
public string ApplicationId { get; set; }
public string ApplicationName { get; set; }
}
Migration 在 DB 中创建了 AspNetApplications 和 ApplicationUserRoles 表。屏幕截图如下。
以下是我的身份模型
public class ApplicationUser : IdentityUser
{
public virtual AspNetApplications AspNetApplication { get; set; }
public virtual ApplicationUserRoles AspNetUserRoles { get; set; }
//public virtual ICollection<AspNetApplicationUsers> AspNetApplicationUsers { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<AspNetApplications> AspNetApplications { get; set; }
public DbSet<ApplicationUserRoles> AspNetUserRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUserRoles>().HasKey(m => new { m.ApplicationId, m.UserId, m.RoleId });
}
}
到目前为止一切都很好,但是现在当我在我的帐户控制器中检查用户时,它仍然从 AspNetUserRoles 带来基于角色的信息。谁能告诉我如何使用我的自定义 ApplicationUserRoles 而不是 IdentityUserRole。
【问题讨论】:
-
你只是想改变 AspNetUserRoles 的表名吗? stackoverflow.com/questions/22855428/…
-
没有。 AspNetUserRoles 表仍然存在,其中包含默认列(UserId 和 RoleId)。最初我尝试将 ApplicationId 添加为 AspNetUserRoles 中的复合键列,但最终遇到了比当前实现迁移更多的问题,迁移创建了一个新表,即 ApplicationUserRole,我希望 UserManager 从此 ApplicationUserRole 表而不是 AspNetUserRole 表中带来角色信息。
-
所以你想要 AspNetUserRoles 表,你就不会使用它?
-
我对 AspNetUserRole 表不感兴趣,因为我有 ApplicationUserRoles 表,这正是我需要的。更详细一点,AspNetUserRole 表只允许每个 UserId 一个角色,但在我的情况下,相同的角色可以分配给相同的用户但在不同的应用程序中,这就是我创建这个新的 ApplicationUserRoles 表的原因。
-
对,所以如果你看到那个链接,你可以更改表名,这样 usermanager 就会使用你的表。
标签: asp.net-mvc asp.net-identity roles asp.net-identity-2