向ASP.Net Identity添加角色时出错

时间:2015-02-03 06:51:49

标签: c# asp.net asp.net-mvc entity-framework asp.net-identity

我的代码就像这样

    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))

有谁可以指出我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

检查DiagnosisContext类是否具有如下有效签名:

public class DiagnosisContext : IdentityDbContext<MyUser>

public class DiagnosisContext : IdentityDbContext

答案 1 :(得分:1)

你的种子方法

protected override void Seed(DiagnosisContext context)

正在接受仅从香草DbContext继承的DiagnosisContext。你应该传递ApplicationDbContext

protected override void Seed(ApplicationDbContext context)

DbContext上没有IdentityRole。