Asp.net mvc 如何扩展Microsoft.AspNet.Identity.EntityFramework.IdentityRole
我希望能够扩展IdentityRole的默认实现,以包括像Description这样的字段。对IdentityUser执行此操作非常简单,因为IdentityDbContext接受IdentityUser类型的泛型参数。但是,IdentityDbContext不允许您为IdentityRole执行此操作。我怎样才能做到这一点 我知道我可以创建一个基本的DbContext,并实现我自己的IUserStore,这样我就可以使用我自己的角色类,但我真的不想这样做 有什么想法吗?Asp.net mvc 如何扩展Microsoft.AspNet.Identity.EntityFramework.IdentityRole,asp.net-mvc,entity-framework,asp.net-mvc-5,asp.net-identity,Asp.net Mvc,Entity Framework,Asp.net Mvc 5,Asp.net Identity,我希望能够扩展IdentityRole的默认实现,以包括像Description这样的字段。对IdentityUser执行此操作非常简单,因为IdentityDbContext接受IdentityUser类型的泛型参数。但是,IdentityDbContext不允许您为IdentityRole执行此操作。我怎样才能做到这一点 我知道我可以创建一个基本的DbContext,并实现我自己的IUserStore,这样我就可以使用我自己的角色类,但我真的不想这样做 有什么想法吗?UserManager使
UserManager
使用UserStore
作为其用户存储(IUserStore
)UserManager
与UserStore
配合使用,将用户添加到角色名中,并将其删除为IUserRole
同样,对于IdentityRole
和RoleStore
也有接口IRole
,TRole
是IdentityRole
。这是为了直接与角色一起工作
因此,您可以继承IdentityRole
并添加其他信息。使用RoleStore
管理附加信息
RoleManager
为角色提供了核心交互方法,可以使用MyRoleStore
MyIdentityRole.cs
public class MyIdentityRole: IdentityRole
{
public String Description { get; set;}
}
我自己也刚刚经历过这种痛苦。事实证明这很简单。只需使用新属性扩展IdentityRole
public class ApplicationRole : IdentityRole
{
public ApplicationRole(string name)
: base(name)
{ }
public ApplicationRole()
{ }
public string Description { get; set; }
}
然后,您需要添加行
new public DbSet<ApplicationRole> Roles { get; set; }
新的公共数据库集角色{get;set;}
像这样插入到ApplicationDbContext类中,否则会出现错误
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{}
new public DbSet<ApplicationRole> Roles { get; set; }
}
public类ApplicationDbContext:IdentityDbContext
{
公共应用程序上下文()
:base(“默认连接”)
{}
新的公共数据库集角色{get;set;}
}
这就是我所需要做的。确保将IdentityRole的所有实例都更改为ApplicationRole,包括正在播种的任何内容。另外,不要忘记发布“更新数据库”以将更改应用于数据库。除非将“ApplicationRole”设置为鉴别器,否则新角色管理器将看不到其中的任何现有行。你可以自己轻松地添加这个
嗯
埃里克但这不是我想要的。我说的是实际的存储机制。IdentityDbContext允许您使用自己的IdentityUser,但它强制使用IdentityRole。上述自定义与IdentityUser的方法相同,不同之处在于存储是RoleStore而不是UserStore。这两个商店都使用IdentityDbContext。IdentityDbContext,自动在IdentityUser中获取这些新字段,但对于IdentityRole,您需要使用OnModelCreating为添加到其中的新字段提供Db映射和约束。感谢您的回答。我想除了将“ApplicationRole”设置为鉴别器之外,我什么都做了。我只是想知道为什么要这么做。。。新的公共数据库集角色{get;set;}