You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to get the database to be created ONLY if it does not exist but am not being successful. I only replaced DropCreateDatabaseAlways() and replaced it with CreateDatabaseIfNotExists(). Do you think that is all I have to do?
Here is what my ApplicationDbInitializer() now looks like:
public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create [email protected] with password=Admin@123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "[email protected]";
const string password = "Admin@123456";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new ApplicationRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
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);
}
}
}
The text was updated successfully, but these errors were encountered:
I don't think you can do that, at least, not from within the code like this. However, under the current configuration, the database should be created when you login as the default admin user defined in the IdentityConfig.cs file.
There may be some way to script this behavior, or you could explore and see if you can find a way to call InitializeDatabaseForEF eariler in the start-up process (I have honestly never looked).
But the standard behavior for code-first here is to run the initialization when the Db is first accessed.
I am trying to get the database to be created ONLY if it does not exist but am not being successful. I only replaced DropCreateDatabaseAlways() and replaced it with CreateDatabaseIfNotExists(). Do you think that is all I have to do?
Here is what my ApplicationDbInitializer() now looks like:
The text was updated successfully, but these errors were encountered: