Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 429
David Kirkpatrick Avatar asked Jun 07 '18 13:06

David Kirkpatrick


1 Answers

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 = "[email protected]",
            NormalizedEmail = "[email protected]".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.

like image 145
theoretisch Avatar answered Oct 09 '22 17:10

theoretisch