I am trying to seed data at startup in preparation for publishing. I want to have the web admin seeded at startup. What I did is
a class
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
- using RoSafety.Data;
- using RoSafety.Models;
- using System.Linq;
-
- namespace RoSafety
- {
- public class RoSafetyDbStartup
- {
- private readonly ApplicationDbContext _context;
-
- public RoSafetyDbStartup(ApplicationDbContext context)
- {
- _context = context;
- }
-
- public async void SeedAdminUser()
- {
- var user = new UserDataClass
- {
- UserName = "[email protected]",
- NormalizedUserName = "[email protected]",
- Email = "[email protected]",
- OrgID = "RS-001",
- NormalizedEmail = "[email protected]",
- EmailConfirmed = true,
- LockoutEnabled = true
- };
- var roleStore = new RoleStore<UserRoleClass>(_context);
-
- if(!_context.Roles.Any(r => r.Name == "AdminNew"))
- {
- await roleStore.CreateAsync(new UserRoleClass { Name = "AdminNew", NormalizedName = "ADMINNEW" });
- }
- if(!_context.Users.Any(u => u.UserName == user.UserName))
- {
- var password = new PasswordHasher<UserDataClass>();
- var hashed = password.HashPassword(user, "vsdrg4gherrhb4re54#RFw");
- user.PasswordHash = hashed;
- var userStore = new UserStore<UserDataClass>(_context);
- await userStore.CreateAsync(user);
- await userStore.AddToRoleAsync(user, "AdminNew");
- }
-
- await _context.SaveChangesAsync();
-
- }
- }
- }
and in statup
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoSafetyDbStartup dbInit)
- {
- .................................other data........................
-
- dbInit.SeedAdminUser();
-
- }
but no data is updated in AspNetUsers or AspNetRoles on database-update
Oh, and my Identity is
- public class UserDataClass : IdentityUser
- {
- ......some data.....
- }
-
- public class UserRoleClass : IdentityRole
- {
- public virtual ICollection<AppIdentityRole> AppUserRoles { get; set; }
- }
-
- public class AppIdentityRole : IdentityUserRole<string>
- {
- public virtual UserDataClass User { get; set; }
- public virtual UserRoleClass Role { get; set; }
- }
What am I doing wrong?