简体   繁体   English

ASP.NET Core 3.1 MVC 中的种子数据库 AspNetUserRoles 表

[英]Seed database AspNetUserRoles table in ASP.NET Core 3.1 MVC

I'm beginner and i work on a Asp.Net Core 3 MVC.我是初学者,我在 Asp.Net Core 3 MVC 上工作。 I'm try to seed AspNetUserRoles table.我正在尝试播种 AspNetUserRoles 表。 User and role work correctly and seeded without errors, but AspNetUserRoles table null.用户和角色正常工作并且没有错误,但 AspNetUserRoles 表 null。 I created seed class like this:我像这样创建了种子 class :

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我已删除 class SeedData,并将此代码添加到 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! PS 感谢马克·迪尼尔·维森特!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM