I am try seeding initial data from my database, but the informacion for this tecnology is really poor. After seek many options, i find i can how send inicial data for IdentityRole and IdentityUser in this post
Entity framework Core with Identity and ASP.NET Core RC2 not creating user in database
But the user say after add service like Transient in ConfigureServices, call in Configure this service, the cuestion is how? Any have idea?
Regards
Archer, to seed data to a database in ASP.NET core you should first create a class, you could call this DbInitializer, and it should look something like this.
public static class DbInitializer
{
public async static void InitializeAync(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
context.Database.EnsureCreated();
// check if any users exist.
if (context.Users.Any())
{
return; // exit method, Database has been seeded
}
string[] roleNames = {"Admin", "Member" };
IdentityResult roleResult;
// loop through roleNames Array
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
//check if role exists
if (!roleExist)
{
// create new role
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//create an array of users
var users = new ApplicationUser[];
{
new ApplicationUser
{
FirstName = "John",
LastName = "doe",
UserName = "johndoe",
Email = "johndoe@email.com",
};
new ApplicationUser
{
FirstName = "James",
LastName = "doe",
UserName = "jamesdoe",
Email = "jamesdoe@email.com",
};
}
//loop through users array
foreach (ApplicationUser _user in users)
{
// create user
await userManager.CreateAsync(_user, "pa$$w0rd");
//add user to "Member" role
await UserManager.AddToRoleAsync(_user, "Member");
}
}
}
Next, you should call your InitializeAsync helper method in the DbInitializer class from the Configure method in the Startup class. like so
public async void Configure( ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
DbInitializer.InitializeAync(context, userManager);
}
and that should do the trick