我的代码是这样的
namespace DiagnosisApp.Models
{
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DiagnosisContext")
{
}
}
}
namespace DiagnosisApp.DAL
{
public class DiagnosisInitializer : DropCreateDatabaseIfModelChanges<DiagnosisContext>
{
protected override void Seed(DiagnosisContext context)
{
var userManager = new UserManager<ApplicationUser>(new
UserStore<ApplicationUser>(context));
var roleManager = new RoleManager<IdentityRole>(new
RoleStore<IdentityRole>(context));
string name = "Admin";
string password = "123456";
//Create Role Admin if it does not exist
if (!roleManager.RoleExists(name))
{
IdentityResult roleresult = roleManager.Create(new IdentityRole(name));
}
//Create User=Admin with password=123456
var user = new ApplicationUser();
user.UserName = name;
IdentityResult adminresult = userManager.Create(user, password);
//Add User Admin to Role Admin
if (adminresult.Succeeded)
{
IdentityResult result = userManager.AddToRole(user.Id, name);
}
base.Seed(context);
}
}
}
namespace DiagnosisApp.DAL
{
public class DiagnosisContext : DbContext
{
public DiagnosisContext()
: base("DiagnosisContext")
{
Database.SetInitializer(new DiagnosisInitializer());
}
}
}
对我来说一切看起来都很好,但这会引发一个错误
实体类型 IdentityRole 不是当前上下文的模型的一部分。
在行
if (!roleManager.RoleExists(name))
谁能指出我在这里做错了什么?
您的种子方法
protected override void Seed(DiagnosisContext context)
接受仅从原版 DbContext 继承的DiagnosisContext
。你应该通过ApplicationDbContext
protected override void Seed(ApplicationDbContext context)
DbContext 上没有 IdentityRole。
检查诊断上下文类是否具有有效的签名,如下所示:
public class DiagnosisContext : IdentityDbContext<MyUser>
或
public class DiagnosisContext : IdentityDbContext