如何在dotnet核心

时间:2017-04-06 19:09:43

标签: c# asp.net asp.net-core

我正在尝试在我的数据库中初始化一些测试数据,并且在Identity Framework中向ApplicationUser添加密码时遇到一些问题。

当我之前完成此操作时,我使用了这样的种子方法:

protected override void Seed(ApplicationDbContext db)
{
    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

    var adminuser = new ApplicationUser { Email = "admin@test.no", UserName = "admin@test.no", 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 = "ola@nordmann.no", Email = "ola@nordmann.no" },
        new ApplicationUser { UserName = "test@test.no", Email = "test@test.no" }
    );
    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 = "test@test.no", Email = "test@test.no" };
    var result1 = userManager.CreateAsync(au1, "Test123");
    db.Users.Add(result1);

2 个答案:

答案 0 :(得分:1)

您可以将PasswordHasher与用户结合使用。

即。

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

db.AddRange(
        new ApplicationUser { UserName = "ola@nordmann.no", Email = "ola@nordmann.no", PasswordHash = hasher.HashPassword(user, "Password1") },

    );
    db.SaveChanges();

答案 1 :(得分:1)

如果其他人感兴趣,我最终得到了以下解决方案:

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

    await userManager.CreateAsync(new ApplicationUser { UserName = "ola@nordmann.no", Email = "ola@nordmann.no"}, "Password1.");
}

并在启动文件的Configure方法中调用此方法,如下所示:

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