我试图在我的MVC5应用程序中使用新的ASP.NET身份,具体来说我正在将ASP.NET Identity集成到现有的数据库中.我已经阅读了关于DB First和ASP.NET Identity的SO的问题/答案,并遵循所有建议,我仍然不能添加角色到我的数据库,虽然我没有添加用户的问题.这是我的代码:
var context = new PayrollDBEntities(); var roleManager = new RoleManager<AspNetRole>(new RoleStore<AspNetRole>(context)); bool roleExists = roleManager.RoleExists(roleDto.Name); if (roleExists){ return false; } var role = new AspNetRole(roleDto.Name){ Name = roleDto.Name,}; IdentityResult result = roleManager.Create(role);//Getting exception here
在代码的最后一行,我收到类型“System.InvalidOperationException”的异常:实体类型IdentityRole不是当前上下文模型的一部分.
这是我的上下文:
public partial class PayrollDBEntities : IdentityDbContext { public PayrollDBEntities() : base("name=PayrollDBEntities") { } public virtual DbSet<AspNetRole> AspNetRoles { get; set; } public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; } public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; } public virtual DbSet<AspNetUser> AspNetUsers { get; set; } ...... }
我的AspNetUser和AspNetRole类派生自IdentityUser和IdentityRole,但是我仍然得到这个异常.这是我的数据库图:
任何帮助将不胜感激.
解决方法
您必须在创建用户商店期间指定使用AspNetRole而不是IdentityRole.您可以使用具有6种类型参数的UserStore类来实现此目的:
new UserStore<AspNetUser,AspNetRole,string,IdentityUserLogin,IdentityUserRole,IdentityUserClaim>(new PayrollDBEntities());
这也表示用户管理器创建时的更改.以下是有关创建所需实例的简化示例:
public class AspNetUser : IdentityUser { /*customization*/ } public class AspNetRole : IdentityRole { /*customization*/ } public class PayrollDBEntities : IdentityDbContext //or : IdentityDbContext <AspNetUser,IdentityUserClaim> { } public class Factory { public IdentityDbContext DbContext { get { return new PayrollDBEntities(); } } public UserStore<AspNetUser,IdentityUserClaim> UserStore { get { return new UserStore<AspNetUser,IdentityUserClaim>(DbContext); } } public UserManager<AspNetUser,string> UserManager { get { return new UserManager<AspNetUser,string>(UserStore); } } public RoleStore<AspNetRole> RoleStore { get { return new RoleStore<AspNetRole>(DbContext); } } public RoleManager<AspNetRole> RoleManager { get { return new RoleManager<AspNetRole>(RoleStore); } } }