blob: f6f156cc2ae7891794d388eb79af5b4ecb1204eb (
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
46
47
48
49
50
51
52
53
54
55
 | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Timeline.Entities;
namespace Timeline.Services.Migration
{
    public interface ICustomMigrationManager
    {
        Task Migrate();
    }
    public class CustomMigrationManager : ICustomMigrationManager
    {
        private IEnumerable<ICustomMigration> _migrations;
        private DatabaseContext _database;
        private ILogger<CustomMigrationManager> _logger;
        public CustomMigrationManager(IEnumerable<ICustomMigration> migrations, DatabaseContext database, ILogger<CustomMigrationManager> logger)
        {
            _migrations = migrations;
            _database = database;
            _logger = logger;
        }
        public async Task Migrate()
        {
            foreach (var migration in _migrations)
            {
                var name = migration.GetName();
                var did = await _database.Migrations.AnyAsync(m => m.Name == name);
                _logger.LogInformation("Found custom migration '{0}'. Did: {1}.", name, did);
                if (!did)
                {
                    _logger.LogWarning("Begin custom migration '{0}'.", name);
                    await using var transaction = await _database.Database.BeginTransactionAsync();
                    await migration.Execute(_database);
                    _database.Migrations.Add(new MigrationEntity { Name = name });
                    await _database.SaveChangesAsync();
                    await transaction.CommitAsync();
                    _logger.LogWarning("End custom migration '{0}'.", name);
                }
            }
        }
    }
}
 |