我試圖初始化我的數據庫中的一些測試數據,並且在Identity Framework中向ApplicationUser添加密碼時遇到一些問題。如何添加ApplicationUser作爲測試數據在dotnet核心
當我已經這樣做了前面,我已經使用這樣的種子方法:
protected override void Seed(ApplicationDbContext db)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var adminuser = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]", FirstName = "admin", LastName = "test" };
userManager.Create(adminuser, "Password1.");
userManager.AddToRole(adminuser.Id, role:"admin");
}
但作爲種子法不DOTNET核心支持我試圖通過以下方式添加虛擬數據:
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
db.Database.EnsureCreated();
db.AddRange(
new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" },
new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }
);
db.SaveChanges();
我還試圖用我的種子方法用同樣的方法,但是,這並不工作,要麼我得到就行了以下錯誤消息是我RESULT1添加到數據庫:
無法從 'System.Threading.Tasks.Task' 轉換爲「Server.Models.ApplicationUser
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var userManager = app.ApplicationServices.GetService<UserManager<ApplicationUser>>();
var au1 = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
var result1 = userManager.CreateAsync(au1, "Test123");
db.Users.Add(result1);
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql#seed-the-database – Alexan