1
- using MaintenanceLog . Data ;
1
+ using System . Threading ;
2
+ using MaintenanceLog . Data ;
2
3
using Microsoft . EntityFrameworkCore ;
4
+ using Microsoft . EntityFrameworkCore . Migrations ;
3
5
4
6
namespace MaintenanceLog ;
5
7
6
8
public static class DatabaseUtility
7
9
{
8
- public static async Task EnsureDbCreatedAndSeedWithDefaults ( DbContextOptions < ApplicationDbContext > options )
10
+ public static async Task EnsureDbCreatedAndSeedWithDefaults ( DbContextOptions < ApplicationDbContext > options , IMigrator migrator )
9
11
{
10
12
var factory = new LoggerFactory ( ) ;
11
13
var builder = new DbContextOptionsBuilder < ApplicationDbContext > ( options )
@@ -20,11 +22,23 @@ public static async Task EnsureDbCreatedAndSeedWithDefaults(DbContextOptions<App
20
22
21
23
try
22
24
{
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 )
24
29
{
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
+ }
28
42
}
29
43
}
30
44
catch ( Exception ex )
0 commit comments