我扩展了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。
答案 0 :(得分:8)
如果您查看IdentityUser
的签名(您的ApplicationUser继承自它)
public class IdentityUser<TKey, TLogin, TRole, TClaim> : IUser<TKey>
where TLogin : Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<TKey>
where TRole : Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<TKey>
where TClaim : Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<TKey>
{
}
您可以看到它接受IdentityUserRole
的自定义定义。
您必须实施的课程MyApplicationUser
必须实现正确的类型:
public class MyApplicationUser : IdentityUser<string, MyUserLogin, ApplicationUserRoles, MyUserClaim>
{
}
和你的角色:
public class MyRole : IdentityRole<string, ApplicationUserRoles>
{
}
和您的ApplicationDbContext
:
public class MyContext : IdentityDbContext<MyUser, MyRole, string, MyUserLogin, ApplicationUserRoles, MyUserClaim>
{
}
和您的UserStore
:
public class MyUserStore: UserStore<MyUser, MyRole, string, MyUserLogin, ApplicationUserRoles, MyUserClaim>
{
public MyUserStore(MyContext context)
: base(context)
{
}
}
我猜应该是它。有一个github repo我在那里玩了一些自定义类和自定义表名。