Asp.net mvc asp.net core 2中的种子数据库用户和角色表

Asp.net mvc asp.net core 2中的种子数据库用户和角色表,asp.net-mvc,database,asp.net-core,asp.net-core-2.0,seed,Asp.net Mvc,Database,Asp.net Core,Asp.net Core 2.0,Seed,我正在从事一个Asp.Net Core 2.0项目,我想为AspnetUser、AspNetRoles和AspNetUserRoles表添加种子。我创建了一个类来种子数据库,如下所示: public class SeedData { public SeedData() { } public static async Task Seeding(UserManager<ApplicationUser> userManager, RoleManager

我正在从事一个Asp.Net Core 2.0项目,我想为
AspnetUser
AspNetRoles
AspNetUserRoles
表添加种子。我创建了一个类来种子数据库,如下所示:

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");    
                }
            }
        }

    }
}
应用程序用户型号:

public class ApplicationRole : IdentityRole
{
    public string Description  { get; set; }
}
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte gender { get; set; }
}
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();

    }
     using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
        }
最后这是我的
程序。cs
类:

public class ApplicationRole : IdentityRole
{
    public string Description  { get; set; }
}
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte gender { get; set; }
}
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();

    }
     using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
        }
一切正常,运行后自动创建应用程序数据库,在
AspNetUsers
AspNetRoles
中创建所有表并插入代码,但存在一个问题。问题是在种子类的
AspNetUserRoles
中没有插入任何行。
我的代码怎么了?

我可以通过在
SeedData
类中更改来解决问题

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 AdminUser",
                     Name = "Admin",
                     NormalizedName = "ADMIN"

                 });

            context.SaveChanges();
        }


        if (!context.Users.Any())
        {
            ApplicationUser user = new ApplicationUser
            {
                FirstName = "MyFirstName",
                LastName = "MyLastName",
                PhoneNumber = "9998885554",
                UserName = "saedbfd",
                NormalizedUserName = "SAEDBFD",
                Email = "MyEmail@Email.com",
                NormalizedEmail="MYEMAIL@EMAIL.COM",
                gender = 1,
                PasswordHash = "AQAAAAEAACcQAAAAEH9MTIiZG90QJrMLt62Zd4Z8O5o5MaeQYYc/53e2GbawhGcx2JNUSmF0pCz9H1AnoA==",
                LockoutEnabled = true,
                SecurityStamp = "aea97aa5-8fb4-40f2-ba33-1cb3fcd54720"
            };

            context.Users.Add(user);
            context.SaveChanges();


            IdentityUserRole<string> ur = new IdentityUserRole<string>();
            ur.RoleId = "b562e963-6e7e-4f41-8229-4390b1257hg6";
            ur.UserId = user.Id;

            context.UserRoles.Add(ur);
            context.SaveChanges();

    }
}
公共类种子数据
{
公共数据()
{
}
公共静态异步任务种子设定(UserManager UserManager、RoleManager RoleManager、ApplicationDbContext上下文)
{
如果(!context.Roles.Any())
{
context.Roles.AddRange(
新应用程序角色
{
Id=“b562e963-6e7e-4f41-8229-4390b1257hg6”,
Description=“这是AdminUser”,
Name=“Admin”,
NormalizedName=“ADMIN”
});
SaveChanges();
}
如果(!context.Users.Any())
{
ApplicationUser用户=新的ApplicationUser
{
FirstName=“MyFirstName”,
LastName=“MyLastName”,
PhoneNumber=“999885554”,
UserName=“saedbfd”,
NormalizedUserName=“SAEDBFD”,
电子邮件=”MyEmail@Email.com",
标准化邮件=”MYEMAIL@EMAIL.COM",
性别=1,
PasswordHash=“aqaaaaaaccqaaaeh9mtiiizg90qjrmlt62zd4z8o5o5maeqyyc/53e2gbawchx2jnusmf0pcz9h1anoa=”,
LockoutEnabled=true,
SecurityStamp=“aea97aa5-8fb4-40f2-ba33-1cb3fcd54720”
};
context.Users.Add(用户);
SaveChanges();
IdentityUserRole ur=新IdentityUserRole();
ur.RoleId=“b562e963-6e7e-4f41-8229-4390b1257hg6”;
ur.UserId=user.Id;
context.UserRoles.Add(ur);
SaveChanges();
}
}
所有数据正确插入数据库,一切正常