private IMigrationsScaffolder CreateMigrationScaffolder <TContext>() where TContext : DbContext, new() { var currentContext = new CurrentDbContext(new TContext()); var idGenerator = new MigrationsIdGenerator(); var code = new CSharpHelper(); var reporter = new TestOperationReporter(); var migrationAssembly = new MigrationsAssembly( currentContext, new DbContextOptions <TContext>().WithExtension(new FakeRelationalOptionsExtension()), idGenerator); var historyRepository = new MockHistoryRepository(); var services = RelationalTestHelpers.Instance.CreateContextServices(); return(new MigrationsScaffolder( new MigrationsScaffolderDependencies( currentContext, new Model(), migrationAssembly, new MigrationsModelDiffer( new FallbackRelationalCoreTypeMapper( TestServiceFactory.Instance.Create <CoreTypeMapperDependencies>(), TestServiceFactory.Instance.Create <RelationalTypeMapperDependencies>(), TestServiceFactory.Instance.Create <TestRelationalTypeMapper>()), new MigrationsAnnotationProvider(new MigrationsAnnotationProviderDependencies()), services.GetRequiredService <IChangeDetector>(), services.GetRequiredService <StateManagerDependencies>(), services.GetRequiredService <CommandBatchPreparerDependencies>()), idGenerator, new MigrationsCodeGeneratorSelector( new[] { new CSharpMigrationsGenerator( new MigrationsCodeGeneratorDependencies(), new CSharpMigrationsGeneratorDependencies( code, new CSharpMigrationOperationGenerator( new CSharpMigrationOperationGeneratorDependencies(code)), new CSharpSnapshotGenerator(new CSharpSnapshotGeneratorDependencies(code)))) }), historyRepository, reporter, new MockProvider(), new SnapshotModelProcessor(reporter), new Migrator( migrationAssembly, historyRepository, services.GetRequiredService <IDatabaseCreator>(), services.GetRequiredService <IMigrationsSqlGenerator>(), services.GetRequiredService <IRawSqlCommandBuilder>(), services.GetRequiredService <IMigrationCommandExecutor>(), services.GetRequiredService <IRelationalConnection>(), services.GetRequiredService <ISqlGenerationHelper>(), services.GetRequiredService <IDiagnosticsLogger <DbLoggerCategory.Migrations> >(), services.GetRequiredService <IDatabaseProvider>())))); }
public static void SetUpMigration() { var primaryConnectionStringKey = DataConfig.GetPrimaryConnectionStringKey(); DataConfig.EnsureDatabaseIsAvailable(connectionStringKey: primaryConnectionStringKey, applicationName: typeof(Program).Assembly.GetName().Name, createLocalDbIfMissing: true, migrationsAssembly: MigrationsAssembly.FromClass <_2014112901_Init>()); }
public DataMigrator(DbContext context, DataMigrationOptions options) { _context = context; _options = options; var contextType = _context.GetType(); var migrationsType = typeof(IDataMigration <>).MakeGenericType(contextType); MigrationsAssembly = string.IsNullOrEmpty(options.MigrationAssembly) ? contextType.Assembly : Assembly.Load(options.MigrationAssembly); _localMigrations = MigrationsAssembly.GetTypes().Where(p => p.GetInterfaces().Any(x => migrationsType.IsAssignableFrom(x))) .ToImmutableDictionary(GetMigrationId, p => p); _invoker = _invokerCache.GetOrAdd(contextType, CreateInoker); }
/// <summary> /// Attempts to load a migrations assembly from the specified path and populate this object /// </summary> public async Task InitializeMigrationsAsync(string pathToMigrations) { Requires.NotNull(pathToMigrations, "pathToMigrations"); // Find files based on the specified glob var file = await _filesRepository.GetMostRecentMatchingFile(pathToMigrations); if (file == null) { throw new ProjectException("Path to migrations dll does not exist", null, this); } // Load migrations assembly MigrationsAssembly = await _assemblyRepository.LoadFromFile(file.FullName); if (MigrationsAssembly == null) { throw new ProjectException("Could not load any migrations from the specified file", null, this); } // Load referenced Fluent Migrator assembly FluentMigratorAssemblyName = await _assemblyRepository.GetReferenceByName(MigrationsAssembly, "FluentMigrator"); if (FluentMigratorAssemblyName == null) { throw new ProjectException("Could not find a reference to the FluentMigrator assembly", null, this); } // Find migration classes var migrationTypes = await _migrationsRepository.GetMigrationTypes(MigrationsAssembly); Migrations = migrationTypes.Select(m => new MigrationInfo(_migrationsRepository, _log, this, m)).ToList(); // Find profile classes var profileTypes = await _migrationsRepository.GetProfileTypes(MigrationsAssembly); Profiles = profileTypes.Select(p => new ProfileInfo(_migrationsRepository, _log, this, p)).ToList(); await Task.WhenAll(Migrations.Select(m => m.InitializeAsync())); await Task.WhenAll(Profiles.Select(p => p.InitializeAsync())); PathToMigrationsDll = pathToMigrations; _log.Info("Loaded {0} migrations and {1} profiles for project '{2}' from assembly {3}, which uses FluentMigrator {4}", Migrations.Count, Profiles.Count, Name, MigrationsAssembly.GetName().Name, FluentMigratorAssemblyName.Version.ToString()); }
private void CreateMigrationAsmFinder() { var currentContext = new Mock <ICurrentDbContext>(); currentContext.Setup(c => c.Context).Returns(new AsmMigrationContext1()); migrationAsm = new MigrationsAssembly(currentContext.Object, dbOptions, Mock.Of <IMigrationsIdGenerator>(), Mock.Of <IDiagnosticsLogger <DbLoggerCategory.Migrations> >()); //Filter out becuase other test asms might be in the list and waiting to be unloaded PrivateObject obj = new PrivateObject(migrationAsm); var asms = (Assembly[])obj.GetField("_autoPocoAssemblies"); asms = asms.Where(c => createdAssemblies.Contains(c)).ToArray(); obj.SetField("_autoPocoAssemblies", asms); }
private IMigrationsScaffolder CreateMigrationScaffolder <TContext>() where TContext : DbContext, new() { var currentContext = new CurrentDbContext(new TContext()); var idGenerator = new MigrationsIdGenerator(); var sqlServerTypeMappingSource = new SqlServerTypeMappingSource( TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>()); var sqlServerAnnotationCodeGenerator = new SqlServerAnnotationCodeGenerator( new AnnotationCodeGeneratorDependencies(sqlServerTypeMappingSource)); var code = new CSharpHelper(sqlServerTypeMappingSource); var reporter = new TestOperationReporter(); var migrationAssembly = new MigrationsAssembly( currentContext, new DbContextOptions <TContext>().WithExtension(new FakeRelationalOptionsExtension()), idGenerator, new FakeDiagnosticsLogger <DbLoggerCategory.Migrations>()); var historyRepository = new MockHistoryRepository(); var services = RelationalTestHelpers.Instance.CreateContextServices(); var model = new Model().FinalizeModel(); model.AddRuntimeAnnotation(RelationalAnnotationNames.RelationalModel, new RelationalModel(model)); return(new MigrationsScaffolder( new MigrationsScaffolderDependencies( currentContext, model, migrationAssembly, new MigrationsModelDiffer( new TestRelationalTypeMappingSource( TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>()), new MigrationsAnnotationProvider( new MigrationsAnnotationProviderDependencies()), services.GetRequiredService <IChangeDetector>(), services.GetRequiredService <IUpdateAdapterFactory>(), services.GetRequiredService <CommandBatchPreparerDependencies>()), idGenerator, new MigrationsCodeGeneratorSelector( new[] { new CSharpMigrationsGenerator( new MigrationsCodeGeneratorDependencies( sqlServerTypeMappingSource, sqlServerAnnotationCodeGenerator), new CSharpMigrationsGeneratorDependencies( code, new CSharpMigrationOperationGenerator( new CSharpMigrationOperationGeneratorDependencies( code)), new CSharpSnapshotGenerator( new CSharpSnapshotGeneratorDependencies( code, sqlServerTypeMappingSource, sqlServerAnnotationCodeGenerator)))) }), historyRepository, reporter, new MockProvider(), new SnapshotModelProcessor(reporter, services.GetRequiredService <IModelRuntimeInitializer>()), new Migrator( migrationAssembly, historyRepository, services.GetRequiredService <IDatabaseCreator>(), services.GetRequiredService <IMigrationsSqlGenerator>(), services.GetRequiredService <IRawSqlCommandBuilder>(), services.GetRequiredService <IMigrationCommandExecutor>(), services.GetRequiredService <IRelationalConnection>(), services.GetRequiredService <ISqlGenerationHelper>(), services.GetRequiredService <ICurrentDbContext>(), services.GetRequiredService <IModelRuntimeInitializer>(), services.GetRequiredService <IDiagnosticsLogger <DbLoggerCategory.Migrations> >(), services.GetRequiredService <IRelationalCommandDiagnosticsLogger>(), services.GetRequiredService <IDatabaseProvider>())))); }
/// <summary> /// Populates the migration lists. /// </summary> /// <param name="plugin">The plugin.</param> /// <param name="appliedMigrationEntries">The applied migration entries.</param> /// <param name="targetMigration">The target migration.</param> /// <param name="migrationsToApply">The migrations to apply.</param> /// <param name="migrationsToRevert">The migrations to revert.</param> /// <param name="actualTargetMigration">The actual target migration.</param> protected virtual void PopulateMigrations( EntityPlugin plugin, IEnumerable <string> appliedMigrationEntries, string targetMigration, out IReadOnlyList <Migration> migrationsToApply, out IReadOnlyList <Migration> migrationsToRevert, out Migration actualTargetMigration) { var appliedMigrations = new Dictionary <string, TypeInfo>(); var unappliedMigrations = new Dictionary <string, TypeInfo>(); var migrations = plugin.GetMigrations().ToList(); if (migrations.Count == 0) { Logger.LogInformation(LoggingEvents.MigrationsNotFoundId, LoggingEvents.MigrationsNotFound, plugin.Name); } // // Determine the set of applied and unapplied migrations. // foreach (var migration in migrations) { var migrationId = migration.GetCustomAttribute <MigrationAttribute>().Id; if (appliedMigrationEntries.Contains(migrationId)) { appliedMigrations.Add(migrationId, migration.GetTypeInfo()); } else { unappliedMigrations.Add(migrationId, migration.GetTypeInfo()); } } // // Build the list of migrations to apply or revert. // if (string.IsNullOrEmpty(targetMigration)) { // // Migrate to latest version. // migrationsToApply = unappliedMigrations .OrderBy(m => m.Key) .Select(p => MigrationsAssembly.CreateMigration(p.Value, DatabaseProvider.Name)) .ToList(); migrationsToRevert = Array.Empty <Migration>(); actualTargetMigration = null; } else if (targetMigration == Migration.InitialDatabase) { // // Migrate to uninstalled. // migrationsToApply = Array.Empty <Migration>(); migrationsToRevert = appliedMigrations .OrderByDescending(m => m.Key) .Select(p => MigrationsAssembly.CreateMigration(p.Value, DatabaseProvider.Name)) .ToList(); actualTargetMigration = null; } else { // // Migrate to specific version. // migrationsToApply = unappliedMigrations .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) <= 0) .OrderBy(m => m.Key) .Select(p => MigrationsAssembly.CreateMigration(p.Value, DatabaseProvider.Name)) .ToList(); migrationsToRevert = appliedMigrations .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) > 0) .OrderByDescending(m => m.Key) .Select(p => MigrationsAssembly.CreateMigration(p.Value, DatabaseProvider.Name)) .ToList(); actualTargetMigration = appliedMigrations .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) == 0) .Select(p => MigrationsAssembly.CreateMigration(p.Value, DatabaseProvider.Name)) .SingleOrDefault(); } }