简体   繁体   中英

Seed database AspNetUserRoles table in ASP.NET Core 3.1 MVC

I'm beginner and i work on a Asp.Net Core 3 MVC. I'm try to seed AspNetUserRoles table. User and role work correctly and seeded without errors, but AspNetUserRoles table null. I created seed class like this:

public class SeedData
    {
        private AppIdentityDbContext _context;

        public SeedData(AppIdentityDbContext context)
        {
            _context = context;
        }
        public async void Initialize()
        {
            var user = new ApplicationUser
            {
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore<IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Id = "b562e963-6e7e-4f42-9339-1235b1234qw5", Name = "admin", NormalizedName = "admin" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "111111Test");
                user.PasswordHash = hashed;

                var userStore = new UserStore<ApplicationUser>(_context);
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "admin");
            }

            IdentityUserRole<string> ur = new IdentityUserRole<string>();
            ur.RoleId = "b562e963-6e7e-4f42-9339-1235b1234qw5";
            ur.UserId = user.Id;

            //await _context.UserRoles.AddAsync(ur);
            await _context.SaveChangesAsync();
        }
    }  

How can i fix this?

Ok, i found another way. I'm removed class SeedData, and added this code in AppIdentityDbContext.cs

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

            builder.Entity<IdentityRole>().HasData(new List<IdentityRole>
            {
                new IdentityRole
                {
                    Id = "1",
                    Name = "admin",
                    NormalizedName = "ADMIN"
                }
            });

            var hasher = new PasswordHasher<ApplicationUser>();
            builder.Entity<ApplicationUser>().HasData(new ApplicationUser
            {
                Id = "1",
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                PasswordHash = hasher.HashPassword(null, "111111Test"),
            });

            builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
            {
                RoleId = "1",
                UserId = "1"
            });
}

Remember to add the migration and update the database.

PS Thx for Mark Deanil Vicente!

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