1.定义WebHostMigrationExtensions类

 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 services = scope.ServiceProvider;
                var logger = services.GetRequiredService<ILogger<TContext>>();
                var context = services.GetService<TContext>();
                try
                {
                    context.Database.Migrate();
                    seeder(context, services);
                    logger.LogInformation($"执行DbContext{typeof(TContext).Name} seed执行成功!");
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"执行DbContext{typeof(TContext).Name} seed执行失败!");
                }
            }

            return host;
        }
    }
public class ApplicationContextSeed
    {
        private UserManager<User> _userManager;

        public async Task SeedAsync(ApplicationDbContext context,IServiceProvider service)
        {
            if (!context.Users.Any())
            {
                _userManager = service.GetRequiredService<UserManager<User>>();
                var defaultUser = new User
                {
                    UserName = "Luna@qq.com",
                    Email = "Luna@qq.com",
                    NormalizedEmail= "Luna@qq.com",
                    NormalizedUserName = "admin"
                };
                var result = await _userManager.CreateAsync(defaultUser, "pwd123456");
                if (!result.Succeeded)
                {
                    throw new Exception("初始化数据库失败");
                }
            }
        }
    }

2.在buildWebHost中调用

public static void Main(string[] args)
        {
            BuildWebHost(args)
            .MigrationDbContext<ApplicationDbContext>((context, services) =>
                {
                    new ApplicationDbContextSeed().SeedAsync(context, services).Wait();
                })
                .Run();
        }

相关文章:

  • 2021-07-14
  • 2021-11-15
  • 2021-05-19
  • 2021-12-30
  • 2021-09-24
  • 2021-10-12
  • 2021-04-25
  • 2021-10-20
猜你喜欢
  • 2021-11-29
  • 2022-12-23
  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案