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


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

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?

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)

        ApplicationUser appUser = new ApplicationUser
            UserName = "tester",
            Email = "",
            NormalizedEmail = "".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");

            new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
            new IdentityRole { Name = "User", NormalizedName = "USER"}

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.

8/29/2018 7:39:15 PM

Related Questions


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