2017-04-06 66 views
0

我試圖初始化我的數據庫中的一些測試數據,並且在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); 
+0

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql#seed-the-database – Alexan

回答

0

如果任何人應該是有興趣的,我結束了以下解決方案:

public async Task CreateUsersAndRoles(IServiceScope serviceScope) 
{ 
    var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>(); 

    await userManager.CreateAsync(new ApplicationUser { UserName = "[email protected]", Email = "[email protected]"}, "Password1."); 
} 

,並在這樣的啓動文件的配置方法中調用此方法:

await CreateUsersAndRoles(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()); 
1

您可以結合使用PasswordHasher與用戶。

var user = new User(); 
var hasher = new PasswordHasher<User>(); 

db.AddRange(
     new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", PasswordHash = hasher.HashPassword(user, "Password1") }, 

    ); 
    db.SaveChanges();