コード例 #1
0
        public void LogHistory(IAppMigration migrationInfo, MigrationResult result, DateTime started, DateTime finished)
        {
            var migrationRecord = new MigrationRecord()
            {
                Id         = migrationInfo.Id,
                Migration  = migrationInfo.Migration,
                Executed   = started,
                Duration   = finished.Subtract(started).Milliseconds,
                Result     = result.Status.ToString(),
                StatusCode = (int)result.Status,
                Message    = result.Message
            };

            MigrationHistory.Add(migrationRecord);
        }
コード例 #2
0
        public static IApplicationBuilder RunAppMigrations(this IApplicationBuilder app)
        {
            var registeredMigrations = app.ApplicationServices.GetServices <IAppMigration>()?
                                       .OrderBy(x => x.Id)
                                       .ThenBy(x => x.Migration);

            using (var scope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                using (var migrationRepo = scope.ServiceProvider.GetRequiredService <MigrationRepository>())
                {
                    if (migrationRepo == null)
                    {
                        throw new NullReferenceException(nameof(MigrationRepository));
                    }

                    foreach (var migration in registeredMigrations)
                    {
                        // Skip migrations that have already been applied
                        if (migrationRepo.HasHistory(migration).Result)
                        {
                            continue;
                        }

                        // else, Run the migration and log results
                        MigrationResult result  = null;
                        DateTime        started = DateTime.Now;

                        try
                        {
                            result = migration.ExecuteAsync().Result;
                        }
                        catch (Exception ex)
                        {
                            result = MigrationResult.Failed(ex.Message);
                        }

                        migrationRepo.LogHistory(migration, result, started, finished: DateTime.Now);
                    }

                    migrationRepo.SaveChanges();
                }
            }

            return(app);
        }