从ASP.NET MVC中添加ApplicationUser

时间:2017-01-11 08:41:36

标签: c# asp.net asp.net-mvc asp.net-mvc-5

我正在尝试播种ASP.NET MVC Web应用程序生成的 ApplicationUser

但是用户不会添加初始化程序。有什么想法吗?

IdentityConfig.cs

{{1}}

ApplicationUserInitializer.cs

{{1}}

1 个答案:

答案 0 :(得分:0)

这就是我的工作方式。 IdentityModels:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }


    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    //dbsets and modelbuilder

IdentityConfig:

public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }

    //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
    public static void InitializeIdentityForEF(ApplicationDbContext db)
    {
        var roleStore = new RoleStore<IdentityRole>(db);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
        var userStore = new UserStore<ApplicationUser>(db);
        var userManager = new UserManager<ApplicationUser>(userStore);

        const string name = "admin@example.com";
        const string password = "Admin@123456";
        const string roleAdmin = "Admin";
        const string roleEmployeer = "Employeer";
        const string roleCandidate = "Candidate";

//just seed whatever here
            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, dateReg = DateTime.Now };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }