我尝试从我的数据库中播种初始数据,但这个技术的信息非常糟糕。在寻找了许多选项之后,我发现我可以在这篇文章中发送IdentityRole和IdentityUser的实际数据
Entity framework Core with Identity and ASP.NET Core RC2 not creating user in database
但是用户说在ConfigureServices中添加像Transient这样的服务后,调用配置这个服务,这个问题是怎么回事?有没有想法?
此致
答案 0 :(得分:3)
Archer,要将数据播种到ASP.NET核心中的数据库,首先应该创建一个类,你可以调用这个DbInitializer,看起来应该是这样的。
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");
}
}
}
接下来,您应该从Startup类中的Configure方法调用DbInitializer类中的InitializeAsync帮助器方法。像这样
public async void Configure( ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
DbInitializer.InitializeAync(context, userManager);
}
这应该可以解决问题