DbMigrationService.cs 1.2 KB

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