SystemsGuy
SystemsGuy

Reputation: 153

Can I use the Configuration.Seed method to an an initial ApplicationUser to an MVC database?

I know that we can initialise the database when doing a Entity Framework migration using the Seed method, as below.

        protected override void Seed(CraigSheppardSoftware.Models.ApplicationDbContext context)
    {
        context.Users.AddOrUpdate(p => p.UserName, 
            new ApplicationUser { FullName = "System Admin", UserName="CssOp", UserRole = UserType.SystemAdmin, 
                LandlinePhone=new ComplexDataTypes.PhoneNumber(), MobilePhone= new ComplexDataTypes.PhoneNumber()
            } );
        context.SaveChanges();
    }

The problem is that the when I try to use that user to login with, I can't as I dont know what the password is.

enter image description here

There is no password field on the database. I notice that there is a PasswordHash field and suspect that this is an encrypted password. How do I create a password hash ?

Upvotes: 1

Views: 359

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

Use UserManager to create / update the user.

var manager = new UserManager<ApplicationUser>(
    new UserStore<ApplicationUser>(context));
var user = manager.Find("CssOp", "ThePassword");
if (user == null)
{
    user = new ApplicationUser { UserName = "CssOp", Email = "[email protected]" };
    manager.Create(user, "ThePassword");
}
else
{
    user.Email = "[email protected]";
    manager.Update(user);
}

Upvotes: 3

Related Questions