DbMigrationService.cs 926 B

123456789101112131415161718192021222324252627282930313233
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.Extensions.Hosting;
  4. using MTWorkHR.Infrastructure.DBContext;
  5. namespace MTWorkHR.Application.StartupService;
  6. public class DbMigrationService : IHostedService
  7. {
  8. private readonly IServiceProvider sp;
  9. public DbMigrationService(IServiceProvider serviceProvider)
  10. {
  11. sp = serviceProvider;
  12. }
  13. public async Task StartAsync(CancellationToken cancellationToken)
  14. {
  15. using (var scope = sp.CreateScope())
  16. {
  17. var identityContext = scope.ServiceProvider.GetRequiredService<HRDataContext>();
  18. // await identityContext.Database.EnsureCreatedAsync(cancellationToken);
  19. await identityContext.Database.MigrateAsync(cancellationToken);
  20. }
  21. }
  22. public Task StopAsync(CancellationToken cancellationToken)
  23. {
  24. return Task.CompletedTask;
  25. }
  26. }