Skip to content

Commit 4c768bf

Browse files
committed
Update migration applying code
1 parent 22a3309 commit 4c768bf

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

src/MaintenanceLog/DatabaseUtility.cs

+20-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
using MaintenanceLog.Data;
1+
using System.Threading;
2+
using MaintenanceLog.Data;
23
using Microsoft.EntityFrameworkCore;
4+
using Microsoft.EntityFrameworkCore.Migrations;
35

46
namespace MaintenanceLog;
57

68
public static class DatabaseUtility
79
{
8-
public static async Task EnsureDbCreatedAndSeedWithDefaults(DbContextOptions<ApplicationDbContext> options)
10+
public static async Task EnsureDbCreatedAndSeedWithDefaults(DbContextOptions<ApplicationDbContext> options, IMigrator migrator)
911
{
1012
var factory = new LoggerFactory();
1113
var builder = new DbContextOptionsBuilder<ApplicationDbContext>(options)
@@ -20,11 +22,23 @@ public static async Task EnsureDbCreatedAndSeedWithDefaults(DbContextOptions<App
2022

2123
try
2224
{
23-
if ((await context.Database.GetPendingMigrationsAsync()).Any())
25+
// not good with distributed UI... but for now...
26+
Console.WriteLine("Applying migrations...");
27+
var migrations = await context.Database.GetPendingMigrationsAsync();
28+
foreach (var migration in migrations)
2429
{
25-
// not good with distributed UI... but for now...
26-
Console.WriteLine("Applying migrations...");
27-
await context.Database.MigrateAsync();
30+
// Execute all migrations in one single transaction
31+
using var tran = await context.Database.BeginTransactionAsync();
32+
try
33+
{
34+
await migrator.MigrateAsync(migration);
35+
await tran.CommitAsync();
36+
}
37+
catch (Exception exc)
38+
{
39+
await tran.RollbackAsync();
40+
throw new Exception($"Error while applying db migration '{migration}'.", exc);
41+
}
2842
}
2943
}
3044
catch (Exception ex)

src/MaintenanceLog/Program.cs

+3-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
using Microsoft.Extensions.Options;
1414
using System.Text.Json;
1515
using Blazored.LocalStorage;
16+
using Microsoft.EntityFrameworkCore.Migrations;
1617

1718
var builder = WebApplication.CreateBuilder(args);
1819

@@ -93,7 +94,8 @@
9394
// handled this way in production.
9495
await using var scope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateAsyncScope();
9596
var options = scope.ServiceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>();
96-
await MaintenanceLog.DatabaseUtility.EnsureDbCreatedAndSeedWithDefaults(options);
97+
var migrator = scope.ServiceProvider.GetService<IMigrator>();
98+
await MaintenanceLog.DatabaseUtility.EnsureDbCreatedAndSeedWithDefaults(options, migrator);
9799

98100
app.MapControllers();
99101

0 commit comments

Comments
 (0)