blob: 6bb8bac005b8a086464a13556dddbd43d1dcd898 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
namespace marlin.web.Services;
using Data;
using Microsoft.EntityFrameworkCore;
public class DatabaseUpgrader : IHostedService
{
private readonly ILogger<DatabaseUpgrader> _logger;
private readonly IServiceProvider _serviceProvider;
public DatabaseUpgrader(ILogger<DatabaseUpgrader> logger, IServiceProvider serviceProvider)
{
this._logger = logger;
this._serviceProvider = serviceProvider;
}
public async Task StartAsync(CancellationToken ct)
{
await using AsyncServiceScope scope = this._serviceProvider.CreateAsyncScope();
DbContext dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var migrations = await dbContext.Database.GetPendingMigrationsAsync(ct);
int pendingCount = migrations.Count();
if (pendingCount == 0)
{
this._logger.LogInformation("Database is up to date.");
return;
}
this._logger.LogInformation("Upgrading database {count} versions.", pendingCount);
try
{
await dbContext.Database.MigrateAsync(ct);
this._logger.LogInformation("Database upgraded.");
}
catch (Exception ex)
{
this._logger.LogError(ex, "Database upgrade failed, {count} behind.", pendingCount);
}
}
public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}
|