Is it possible/advisable to seed Users/Roles using the EFCore 2.1 Data Seeding system?

asp.net-core entity-framework-core

Question

As of EFCore 2.1 it's possible to seed data using the DbContext OnModelCreating method.

https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding

However user/role creation is usually handled by a UserManager/RoleManager.

Now, I can manually create a Role or User - but for example in the case of a User I need to hash the password myself (and I don't know what hashing method is used by the UserManager without digging into the source)

Is there any way around this? Or should I stick with having a static seeding method that runs on startup as in previous versions of Entity Framework Core?

1
4
6/7/2018 1:39:49 PM

Accepted Answer

If you want to use the OnModelCreating method with the HasData method you can do it like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        ApplicationUser appUser = new ApplicationUser
        {
            UserName = "tester",
            Email = "tester@test.com",
            NormalizedEmail = "tester@test.com".ToUpper(),
            NormalizedUserName = "tester".ToUpper(),
            TwoFactorEnabled = false,
            EmailConfirmed = true,
            PhoneNumber = "123456789",
            PhoneNumberConfirmed = false
        };

        PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>();
        appUser.PasswordHash = ph.HashPassword(appUser, "Your-PW1");

        modelBuilder.Entity<IdentityRole>().HasData(
            new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
            new IdentityRole { Name = "User", NormalizedName = "USER"}
        );
        modelBuilder.Entity<ApplicationUser>().HasData(
            appUser
        );
    }

If you create the user outside the HasData method you can use the PasswordHasher. It will hash the password for you. Then just put the created user into HasData instead of creating a new one there. I don't know if that's better than the seeding on startup, but its one way to do it.

3
8/29/2018 7:39:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow