问题描述
我希望能够扩展 IdentityRole 的默认实现以包含像描述这样的字段.对 IdentityUser 执行此操作很容易,因为 IdentityDbContext 采用 IdentityUser 类型的通用参数.但是,IdentityDbContext 不允许您为 IdentityRole 执行此操作.我怎样才能做到这一点?
I want to be able to extend the default implementation of IdentityRole to include fields like Description. It's easy enough to do this for IdentityUser because IdentityDbContext takes a generic parameter of type IdentityUser. However, IdentityDbContext doesn't allow you to do this for IdentityRole. How can I accomplish this?
我知道我可以创建一个基本的 DbContext,并实现我自己的 IUserStore,这样我就可以使用我自己的角色类,但我真的不想这样做.
I know I can create a basic DbContext, and implement my own IUserStore, so that I can use my own role class, but I really don't want to have to do that.
有什么想法吗?
推荐答案
我自己刚刚经历了这种痛苦.事实证明它非常简单.只需使用您的新属性扩展 IdentityRole.
I have just gone through this pain myself. It actually turned out to be pretty simple. Just extend IdentityRole with your new properties.
public class ApplicationRole : IdentityRole
{
public ApplicationRole(string name)
: base(name)
{ }
public ApplicationRole()
{ }
public string Description { get; set; }
}
然后你需要添加一行
new public DbSet<ApplicationRole> Roles { get; set; }
像这样进入你的 ApplicationDbContext 类,否则你会得到错误.
into your ApplicationDbContext class like this otherwise you will get errors.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{}
new public DbSet<ApplicationRole> Roles { get; set; }
}
这就是我需要做的.确保将 IdentityRole 的所有实例更改为 ApplicationRole,包括您正在播种的任何内容.另外,不要忘记发出更新数据库"以将更改应用于您的数据库.除非您将ApplicationRole"设置为鉴别器,否则您的新 RoleManager 不会看到其中的任何现有行.您可以轻松地自行添加.
thats all I needed to do. Make sure you change all instances of IdentityRole to ApplicationRole including anything you are seeding. Also, dont forget to issue a "update-database" to apply the changes to your DB. Any existing rows in there won't be seen by your new RoleManager unless you have the "ApplicationRole" set as a discriminator. You can easily add this yourself.
HTH
埃里克
这篇关于如何扩展 Microsoft.AspNet.Identity.EntityFramework.IdentityRole的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!