1-创建一个可以启动时如果没有一个账号刚创建1个新的账号
namespace MvcCookieAuthSample.Data { public class ApplicationDbContextSeed { public async Task SeedAsync(ApplicationDbContext context, IServiceProvider service) { if (!context.Users.Any()) { var _userManager= service.GetRequiredService<UserManager<ApplicationUser>>(); var user = new ApplicationUser() { Email="qinzhb@163.com", UserName="qinzhb", NormalizedUserName="qinzhb" }; var result = await _userManager.CreateAsync(user, "123456@Byd"); if (!result.Succeeded) { throw new Exception("初始化用户失败"); } } } } }
2-增加一个扩展方法,用于启动时初始化数据库
namespace MvcCookieAuthSample { public static class WebHostMigrationExtensions { public static IWebHost MigrationDbContext<TContext>(this IWebHost host,Action<TContext ,IServiceProvider> seeder) where TContext:DbContext { using (var scope = host.Services.CreateScope()) { var service = scope.ServiceProvider; var logger = service.GetRequiredService<ILogger<TContext>>(); var context = service.GetService<TContext>(); try { context.Database.Migrate(); seeder(context, service); logger.LogInformation("执行方法数据库初始化成功"); } catch { logger.LogError("执行数据库数据库初始化密码失败"); } } return host; } } }
3-把上面的2方法增加到启动类中
public static void Main(string[] args) { CreateWebHostBuilder(args) .Build() .MigrationDbContext<ApplicationDbContext>((context,services)=> { new Data.ApplicationDbContextSeed().SeedAsync(context, services).Wait(); }).Run(); }