简体   繁体   中英

How to add ApplicationUser as test data in dotnet core

I'm trying to initialize some test data in my database, and having some problems adding password to the ApplicationUser in Identity Framework.

When I have done this earlier, I have used the seed method like this:

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");
}

but as the seed method is not supported in dotnet core I have tried to add the dummy data in the following way:

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();

I have also tried to use the same method I used in the seed method, but that doesn't work either as I get the following error message on the line were I add result1 to the database:

cannot convert from 'System.Threading.Tasks.Task' to '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);

You can use PasswordHasher in combination with user.

ie

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();

If anyone else should be interested, I ended up with the following solution:

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.");
}

and call on this method within the Configure method in the startup file like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM