asp.net core 中实现DBContext的初始化,先创建一个ApplicationDBContextSeed,作为初始化基础数据的类,
需要引用 using Microsoft.Extensions.DependencyInjection 和 using Microsoft.Extensions.Logging ,只有在初始化创建数据库的时候将默认的admin账号写入表中
public class ApplicationDBContextSeed { private UserManager<ApplicationUser> _userManager; public async Task SeedAsync(ApplicationDBContext contest,IServiceProvider serviceProvider) { if (!contest.Users.Any()) { _userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var defultUser = new ApplicationUser { UserName = "admin", Email = "leo@qq.com", NormalizedUserName = "admin" }; var resilt= await _userManager.CreateAsync(defultUser, "123456"); if(!resilt.Succeeded) { throw new Exception("初始化用户信息失败!"); } } } }
创建WebHostMirgationExtensions
public static class WebHostMirgationExtensions { public static IWebHost MigrateDbContext<TContext>(this IWebHost host,Action<TContext,IServiceProvider> sedder) where TContext:DbContext { using (var scope =host.Services.CreateScope()) { var services = scope.ServiceProvider; var logger = services.GetRequiredService<ILogger<TContext>>(); var context = services.GetService<TContext>(); try { context.Database.Migrate();//每次执行都会自动去更新数据库 sedder(context, services); logger.LogInformation($"执行DBContext:{typeof(TContext).Name} seed方法成功"); } catch (Exception ex) { logger.LogError(ex, $"执行DBContext:{typeof(TContext).Name} seed方法失败"); } } return host; } }
修改Program
public static void Main(string[] args) { BuildWebHost(args) .MigrateDbContext<ApplicationDBContext>((context, server) => { new ApplicationDBContextSeed().SeedAsync(context, server).Wait(); } ).Run(); }