asp.net核心2中的种子数据库用户和角色表

时间:2018-04-22 22:23:43

标签: asp.net-mvc database asp.net-core asp.net-core-2.0 seed

我正在开发Asp.Net Core 2.0项目,我希望对AspnetUserAspNetRolesAspNetUserRoles表进行种子处理。我创建了一个种子数据库的类,如下所示:

public class SeedData
{

    public SeedData()
    {

    }

    public static async Task Seeding(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ApplicationDbContext context)
    {
        if (!context.Roles.Any())
        {

            context.Roles.AddRange(
                 new ApplicationRole
                 {
                     Id = "b562e963-6e7e-4f41-8229-4390b1257hg6",
                     Description = "This Is Admin User",
                     Name = "Admin",
                     NormalizedName = "ADMIN"

                 });
            context.SaveChanges();
        }


        if (!context.Users.Any())
        {
            ApplicationUser user = new ApplicationUser
            {
                FirstName = "MyName",
                LastName = "MyFamily",
                PhoneNumber = "9998885554",
                UserName = "saedbfd",
                Email = "myEmail@email.com",
                gender = 1
            };

            IdentityResult result = await userManager.CreateAsync(user, "123aA@");
            if (result.Succeeded)
            {
                ApplicationRole approle = await roleManager.FindByIdAsync("b562e963-6e7e-4f41-8229-4390b1257hg6");
                if (approle != null)
                {
                    await userManager.AddToRoleAsync(user, "Admin");    
                }
            }
        }

    }
}

上面的代码是我的种子类,它在3个表中插入数据:AspNetUsers,AspNetRolse和AspNetUserRoles

ApplicationRole型号:

public class ApplicationRole : IdentityRole
{
    public string Description  { get; set; }
}

ApplicationUser Model:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte gender { get; set; }
}

最后这是我的Program.cs班级:

public class Program
{

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
                var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
                var context = services.GetRequiredService<ApplicationDbContext>();
                SeedData.Seeding(userManager,roleManager,context);//<---Do your seeding here
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

        public static IWebHost BuildWebHost(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .Build();

    }

我将此代码添加到configure中的startup.cs方法:

     using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
        }

Everithing很好,运行后应用程序数据库自动创建并创建所有表并在AspNetUsersAspNetRoles中插入重新编码,但是存在问题。该问题未在种子类中的AspNetUserRoles中插入任何行。 我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

我可以通过更改Java.util.regex.patternSyntacexception: illegal repetition near index 0 ${YMODULE_TOKEN}(.*)

来解决我的问题
SeedData

所有数据都在数据库中正确插入,一切正常。