问题
I am having trouble seeding users in my .net core 3.1 web app. The corresponding tables are being created on SQL Server, but no rows are being created when I run my app. I don't know why the database isn't being populated. Can anybody spot the issue?
DBInitializer file to seed users into database
public class DBInitializer
{
public static async Task Initialize(IServiceProvider services)
{
ApplicationDbContext database = services.GetRequiredService<ApplicationDbContext>();
UserManager<ApplicationUser> userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
RoleManager<IdentityRole> roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
string roleA = "A";
string roleB = "B";
if (!database.Roles.Any())
{
IdentityRole role = new IdentityRole(roleA);
await roleManager.CreateAsync(role);
IdentityRole roleOne = new IdentityRole(roleB);
await roleManager.CreateAsync(roleOne);
await database.SaveChangesAsync();
}
if (!database.ApplicationUsers.Any())
{
AppUserA appUser = new AppUserA("App", "UserA", "AppUserA1@wmu.edu",
"306.000.0001", "AppUserA1");
await userManager.CreateAsync(appUser);
await userManager.AddToRoleAsync(appUser, roleA);
AppUserB appUserFour = new AppUserB("App", "UserB1", "AppUserB1@wmu.edu",
"306.000.0001", "AppUserB1");
await userManager.CreateAsync(appUserFour);
await userManager.AddToRoleAsync(appUserFour, roleA);
await database.SaveChangesAsync();
}
ApplicationUser class that extends Asp.net IdentityUser class
public class ApplicationUser : IdentityUser
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String FullName => FirstName + " " + LastName;
public ApplicationUser()
{
}
public ApplicationUser(string firstName, string lastName, string email, string phoneNumber, string password)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Email = email;
this.PhoneNumber = phoneNumber;
this.UserName = email;
PasswordHasher<ApplicationUser> passwordHasher = new PasswordHasher<ApplicationUser>();
this.PasswordHash = passwordHasher.HashPassword(this, password);
this.SecurityStamp = Guid.NewGuid().ToString();
}
AppUserA Class that extends applicationuser
public class AppUserA : ApplicationUser
{
public AppUserA()
{
}
public AppUserA(string firstName, string lastName, string email, string phoneNumber, string password)
: base(firstName, lastName, email, phoneNumber, password)
{
}
}
ApplicationDBContext file:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<AppUserA> AppUserAs { get; set; }
public DbSet<AppUserB> AppUserBs { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
回答1:
Here is a working demo like below:
1.Model:
public class ApplicationUser : IdentityUser
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String FullName => FirstName + " " + LastName;
public ApplicationUser()
{
}
public ApplicationUser(string firstName, string lastName, string email, string phoneNumber, string password)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Email = email;
this.PhoneNumber = phoneNumber;
this.UserName = email;
PasswordHasher<ApplicationUser> passwordHasher = new PasswordHasher<ApplicationUser>();
this.PasswordHash = passwordHasher.HashPassword(this, password);
this.SecurityStamp = Guid.NewGuid().ToString();
}
}
public class AppUserA : ApplicationUser
{
public AppUserA()
{
}
public AppUserA(string firstName, string lastName, string email, string phoneNumber, string password)
: base(firstName, lastName, email, phoneNumber, password)
{
}
}
public class AppUserB : ApplicationUser
{
public AppUserB()
{
}
public AppUserB(string firstName, string lastName, string email, string phoneNumber, string password)
: base(firstName, lastName, email, phoneNumber, password)
{
}
}
2.Program.cs:
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
CreateDbIfNotExists(host);
host.Run();
//CreateHostBuilder(args).Build().Run();
}
private static async Task CreateDbIfNotExists(IHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
await DBInitializer.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
3.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllersWithViews();
services.AddRazorPages();
}
Result:
来源:https://stackoverflow.com/questions/60581580/why-arent-my-identityroles-and-applicationusers-populating-into-my-database