public DbMigratorEventArgs(DbMigrationsConfiguration migrationConfiguration) { this.MigrationConfiguration = migrationConfiguration; DbMigrator migrator = new DbMigrator(migrationConfiguration); this.PendingMigrations = migrator.GetPendingMigrations(); this.CompletedMigrations = migrator.GetDatabaseMigrations(); }
public QueueFixture() { try { var configuration = new DbMigrationsConfiguration { ContextType = typeof(QueueDataContext), MigrationsAssembly = typeof(QueueDataContext).Assembly, TargetDatabase = new DbConnectionInfo("QueueDataContext"), MigrationsNamespace = typeof(InitialCreate).Namespace, AutomaticMigrationDataLossAllowed = true }; var migrator = new DbMigrator(configuration); //Update / rollback to "MigrationName" migrator.Update("0"); migrator.Update(); _sut = new SqlQueueImpl(new Infrastructure.DatabaseContextFactory()); } catch (Exception ex) { if (Debugger.IsAttached) Debugger.Break(); Console.WriteLine(ex); throw; } }
private static DbMigrator GetMigrator() { var migContext = new DbMigrationsConfiguration<DiscoDataContext>(); migContext.MigrationsAssembly = typeof(DiscoDataMigrator).Assembly; migContext.MigrationsNamespace = "Disco.Data.Migrations"; return new DbMigrator(migContext); }
/// <summary> /// For testing. /// </summary> internal DbMigrator(DbContext usersContext = null, DbProviderFactory providerFactory = null) : base(null) { _contextForInterception = usersContext; _providerFactory = providerFactory; _usersContextInfo = new DbContextInfo(typeof(DbContext)); _configuration = new DbMigrationsConfiguration(); }
public void Can_add_and_get_sql_generator() { var migrationsConfiguration = new DbMigrationsConfiguration(); var migrationSqlGenerator = new SqlServerMigrationSqlGenerator(); migrationsConfiguration.SetSqlGenerator(DbProviders.Sql, migrationSqlGenerator); Assert.Same(migrationSqlGenerator, migrationsConfiguration.GetSqlGenerator(DbProviders.Sql)); }
public void Can_get_and_set_migration_context_properties() { var migrationsConfiguration = new DbMigrationsConfiguration { AutomaticMigrationsEnabled = false, ContextType = typeof(ShopContext_v1), CodeGenerator = new Mock<MigrationCodeGenerator>().Object }; Assert.False(migrationsConfiguration.AutomaticMigrationsEnabled); Assert.NotNull(migrationsConfiguration.CodeGenerator); Assert.Equal(typeof(ShopContext_v1), migrationsConfiguration.ContextType); }
// <summary> // For testing. // </summary> internal DbMigrator( DbContext usersContext = null, DbProviderFactory providerFactory = null, MigrationAssembly migrationAssembly = null) : base(null) { _usersContext = usersContext; _providerFactory = providerFactory; _migrationAssembly = migrationAssembly; _usersContextInfo = new DbContextInfo(typeof(DbContext)); _configuration = new DbMigrationsConfiguration(); _calledByCreateDatabase = true; }
/// <summary> /// Initializes a new instance of the <see cref="DbMigrator"/> class. /// </summary> /// <param name="configuration">Configuration to be used for the migration process.</param> public DbMigrator(DbMigrationsConfiguration configuration) : base(configuration) { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (_usersContextInfo.IsConstructible) { using (var context = _usersContextInfo.CreateInstance()) { DbMigrationContext.Current.DatabaseName = context.Database.Connection.Database; } } }
/// <summary> /// Run Automatic migrations /// </summary> internal static void UpdateAutoMigrations(string name, DbMigrationsConfiguration<DataContext> migrationConfig) { DbMigrationsConfiguration config = migrationConfig ?? new DbMigrationsConfiguration<DataContext> { AutomaticMigrationsEnabled = true, AutomaticMigrationDataLossAllowed = false, //TargetDatabase = new DbConnectionInfo(name), }; Console.WriteLine("Migrator: " + config.GetType().ToString()); config.ContextType = typeof(DataContext); config.TargetDatabase = new DbConnectionInfo(name); var migrator = new DbMigrator(config); migrator.Update(); }
public void Can_use_custom_operations() { var configuration = new DbMigrationsConfiguration<EmptyModel> { MigrationsAssembly = typeof(CustomOperationMigration).Assembly(), MigrationsNamespace = typeof(CustomOperationMigration).Namespace }; configuration.SetSqlGenerator("System.Data.SqlClient", new CustomSqlGenerator()); var migrator = new DbMigrator(configuration); var scriptor = new MigratorScriptingDecorator(migrator); var sql = scriptor.ScriptUpdate(DbMigrator.InitialDatabase, null); Assert.Contains("-- This is a test.", sql); }
private static void SetSqlGeneratorTest(bool setGenerator) { var generator = new Mock<MigrationSqlGenerator>().Object; var mockResolver = new Mock<IDbDependencyResolver>(); mockResolver.Setup(m => m.GetService(typeof(MigrationSqlGenerator), "Gu.Hu.Ha")).Returns(generator); var mockConfiguration = new Mock<DbConfiguration>(); mockConfiguration.Setup(m => m.DependencyResolver).Returns(mockResolver.Object); var migrationsConfiguration = new DbMigrationsConfiguration(new Lazy<DbConfiguration>(() => mockConfiguration.Object)); if (setGenerator) { generator = new Mock<MigrationSqlGenerator>().Object; migrationsConfiguration.SetSqlGenerator("Gu.Hu.Ha", generator); } Assert.Same(generator, migrationsConfiguration.GetSqlGenerator("Gu.Hu.Ha")); }
static void ResetDb() { using (var context = new DbContext("DefaultConnection")) { context.Database.Delete(); } // recreate the database with migrations var configs = new DbMigrationsConfiguration[] { new Migrations.BookContextMigrations.Configuration(), new Migrations.UserContextMigrations.Configuration() }; foreach (var config in configs) { var migrator = new DbMigrator(config); migrator.Update(); } }
public MigrationChangedEventArgs(DbMigrationsConfiguration migrationConfiguration, string migrationName) : base(migrationConfiguration) { this.MigrationName = migrationName; }
protected override void ModifyMigrationsConfiguration(DbMigrationsConfiguration configuration) { configuration.CodeGenerator.AnnotationGenerators[CollationAttribute.AnnotationName] = () => new CollationCSharpCodeGenerator(); }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = calledByCreateDatabase; _existenceState = existenceState; if (usersContext != null) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); _usersContext = context; try { _migrationAssembly = new MigrationAssembly( _configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); _connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(_connection); _defaultSchema = context.InternalContext.DefaultSchema ?? EdmModelExtensions.DefaultSchema; _historyContextFactory = _configuration .GetHistoryContextFactory(_usersContextInfo.ConnectionProviderName); _historyRepository = new HistoryRepository( context.InternalContext, _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, _configuration.CommandTimeout, _historyContextFactory, schemas: new[] { _defaultSchema }.Concat(GetHistorySchemas()), contextForInterception: _usersContext, initialExistence: _existenceState); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .DependencyResolver .GetService<IManifestTokenResolver>() .ResolveManifestToken(_connection); var modelBuilder = context.InternalContext.CodeFirstModel.CachedModelBuilder; _modificationCommandTreeGenerator = new Lazy<ModificationCommandTreeGenerator>( () => new ModificationCommandTreeGenerator( modelBuilder.BuildDynamicUpdateModel( new DbProviderInfo( _usersContextInfo.ConnectionProviderName, _providerManifestToken)), CreateConnection())); var interceptionContext = new DbInterceptionContext(); interceptionContext = interceptionContext.WithDbContext(_usersContext); _targetDatabase = Strings.LoggingTargetDatabaseFormat( DbInterception.Dispatch.Connection.GetDataSource(_connection, interceptionContext), DbInterception.Dispatch.Connection.GetDatabase(_connection, interceptionContext), _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.DefaultContextKey; _emptyModel = GetEmptyModel(); } finally { if (usersContext == null) { _usersContext = null; context.Dispose(); } } }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : base(null) { Contract.Requires(configuration != null); Contract.Requires(configuration.ContextType != null); _configuration = configuration; _calledByCreateDatabase = usersContext != null; // If DbContext CreateDatabase is using Migrations then the user has not opted out of initializers // and if we disable the initializer here then future calls to Initialize the database (for this or // a different connection) will fail. So only disable the initializer if Migrations are being used // explicitly. if (usersContext == null) { DisableInitializer(_configuration.ContextType); } if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); try { _migrationAssembly = new MigrationAssembly(_configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); _defaultSchema = context.InternalContext.DefaultSchema; var historySchemas = GetHistorySchemas(); if (!string.IsNullOrWhiteSpace(_defaultSchema)) { historySchemas = historySchemas.Concat(new[] { _defaultSchema }); } _historyRepository = new HistoryRepository(_usersContextInfo.ConnectionString, _providerFactory, historySchemas); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbProviderServices.GetProviderServices(connection). GetProviderManifestTokenChecked(connection); _targetDatabase = Strings.LoggingTargetDatabaseFormat( connection.DataSource, connection.Database, _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); } finally { if (usersContext == null) { context.Dispose(); } } var providerInfo = new DbProviderInfo(_usersContextInfo.ConnectionProviderName, _providerManifestToken); _emptyModel = new Lazy<XDocument>(() => new DbModelBuilder().Build(providerInfo).GetModel()); _historyRepository.AppendHistoryModel(_currentModel, providerInfo); }
public OAuthDbMigrator(DbMigrationsConfiguration configuration) : base(configuration) { }
public ConnectionStringChangedEventArgs(DbMigrationsConfiguration migrationConfiguration, ConnectionStringSettings setting) : base(migrationConfiguration) { this.ConnectionStringSetting = setting; }
private void DatabaseMigrator_MigrationTargetChanged(object sender, MigrationTargetChangedEventArgs e) { _currentConfiguration = e.MigrationConfiguration; lblMigrationTarget.Text = e.MigratorTitle; cmbMigrationTarget.Text = e.MigratorTitle; UpdateMigrationLists(e); }
public void Uses_ExecutionStrategy() { var configuration = new DbMigrationsConfiguration { ContextType = typeof(ShopContext_v1), MigrationsAssembly = SystemComponentModelDataAnnotationsAssembly, MigrationsNamespace = typeof(ShopContext_v1).Namespace, HistoryContextFactory = (e, d) => new HistoryContext(e, d) }; var migrator = new DbMigrator(configuration); var executionStrategyMock = new Mock<IExecutionStrategy>(); MutableResolver.AddResolver<Func<IExecutionStrategy>>(key => (Func<IExecutionStrategy>)(() => executionStrategyMock.Object)); try { migrator.ExecuteStatements(Enumerable.Empty<MigrationStatement>()); } finally { MutableResolver.ClearResolvers(); } executionStrategyMock.Verify(m => m.Execute(It.IsAny<Action>()), Times.Once()); }
/// <summary> /// Получить список столбцов которые будут удалены /// </summary> /// <param name="configuration">Конфигурация миграций</param> /// <returns>Список столбцов которые будут удалены</returns> private IEnumerable<ColumnInfo> GetDroppingColumnFromMigrationsConfiguration(DbMigrationsConfiguration configuration) { var droppingColumn = new List<ColumnInfo>(); if (configuration != null) { var migrator = new DbMigrator(configuration); var pendingMigrations = migrator.GetPendingMigrations(); if (pendingMigrations.Any()) { var targetMigration = pendingMigrations.Last(); var scriptor = new MigratorScriptingDecorator(migrator); string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: targetMigration); var parts = script.Split(new[] {"\r\n\r\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries).ToList();//разбиваем скрипт по миграциям parts.RemoveAll(p => p.StartsWith("INSERT [dbo].[__MigrationHistory]") || p.StartsWith("VALUES"));//удаляем вставки в MigrationHistory var dropColumnParts = parts.Where(p => p.Contains("DROP COLUMN"));//находим DROP COLUMN foreach (var dropColumnPart in dropColumnParts) { Regex regex = new Regex("ALTER TABLE (?<schemaWithTable>.*) DROP COLUMN (?<column>.*)"); Match match = regex.Match(dropColumnPart); string[] schemaWithTable = match.Groups["schemaWithTable"].Value.Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); string schema = schemaWithTable.First(); string table = schemaWithTable.Last(); string column = match.Groups["column"].Value.Trim(new[] { '[', ']' }); droppingColumn.Add(new ColumnInfo(new TableInfo(schema, table), column)); } } } return droppingColumn; }
public MigrationsZsValidateProvider(string connectionName, DbMigrationsConfiguration migrationsConfiguration, string label) { _connectionName = connectionName; _migrationsConfiguration = migrationsConfiguration; _label = label; }
public ExternalConfiguration() { _configuration = new Migrations.Configuration(); }
/// <summary> /// Initializes a new instance of the DbMigrator class. /// </summary> /// <param name="configuration"> Configuration to be used for the migration process. </param> public DbMigrator(DbMigrationsConfiguration configuration) : this(configuration, null, DatabaseExistenceState.Unknown, calledByCreateDatabase: false) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); }
/// <summary> /// Initializes a new instance of the DbMigrator class. /// </summary> /// <param name="configuration"> Configuration to be used for the migration process. </param> public DbMigrator(DbMigrationsConfiguration configuration) : this(configuration, null) { Contract.Requires(configuration != null); Contract.Requires(configuration.ContextType != null); }
/// <summary> /// Initializes a new instance of the DbMigrator class. /// </summary> /// <param name="configuration"> Configuration to be used for the migration process. </param> public DbMigrator(DbMigrationsConfiguration configuration) : this(configuration, null, DatabaseExistenceState.Unknown) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = usersContext != null; _existenceState = existenceState; if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); _contextForInterception = context; try { _migrationAssembly = new MigrationAssembly( _configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); _defaultSchema = context.InternalContext.DefaultSchema ?? EdmModelExtensions.DefaultSchema; _historyContextFactory = _configuration .GetHistoryContextFactory(_usersContextInfo.ConnectionProviderName); _historyRepository = new HistoryRepository( _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, _configuration.CommandTimeout, _historyContextFactory, schemas: new[] { _defaultSchema }.Concat(GetHistorySchemas()), contextForInterception: _contextForInterception, initialExistence: _existenceState); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .DependencyResolver .GetService <IManifestTokenResolver>() .ResolveManifestToken(connection); var modelBuilder = context.InternalContext.CodeFirstModel.CachedModelBuilder; _modificationCommandTreeGenerator = new Lazy <ModificationCommandTreeGenerator>( () => new ModificationCommandTreeGenerator( modelBuilder.BuildDynamicUpdateModel( new DbProviderInfo( _usersContextInfo.ConnectionProviderName, _providerManifestToken)), CreateConnection())); var interceptionContext = new DbInterceptionContext(); interceptionContext = interceptionContext.WithDbContext(_contextForInterception); _targetDatabase = Strings.LoggingTargetDatabaseFormat( DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext), DbInterception.Dispatch.Connection.GetDatabase(connection, interceptionContext), _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.DefaultContextKey; _emptyModel = GetEmptyModel(); } finally { if (usersContext == null) { _contextForInterception = null; context.Dispose(); } } }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = usersContext != null; // If DbContext CreateDatabase is using Migrations then the user has not opted out of initializers // and if we disable the initializer here then future calls to Initialize the database (for this or // a different connection) will fail. So only disable the initializer if Migrations are being used // explicitly. if (usersContext == null) { DisableInitializer(_configuration.ContextType); } if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); _contextForInterception = context; try { _migrationAssembly = new MigrationAssembly( _configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); _defaultSchema = context.InternalContext.DefaultSchema ?? EdmModelExtensions.DefaultSchema; _historyRepository = new HistoryRepository( _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, _configuration.CommandTimeout, new[] { _defaultSchema }.Concat(GetHistorySchemas()), _configuration.HistoryContextFactory); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .GetService<IManifestTokenService>() .GetProviderManifestToken(connection); _modificationCommandTreeGenerator = new ModificationCommandTreeGenerator( context.GetDynamicUpdateModel( new DbProviderInfo( _usersContextInfo.ConnectionProviderName, _providerManifestToken)), CreateConnection()); _targetDatabase = Strings.LoggingTargetDatabaseFormat( connection.DataSource, connection.Database, _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.ContextKey; _emptyModel = GetEmptyModel(); } finally { if (usersContext == null) { _contextForInterception = null; context.Dispose(); } } }
/// <summary> /// Initializes a new instance of the DbMigrator class. /// </summary> /// <param name="configuration"> Configuration to be used for the migration process. </param> public DbMigrator(DbMigrationsConfiguration configuration) : this(configuration, null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); }
public MigrationTargetChangedEventArgs(DbMigrationsConfiguration migrationConfiguration, string migratorTitle) : base(migrationConfiguration) { MigratorTitle = migratorTitle; }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : this(configuration, usersContext, DatabaseExistenceState.Unknown, calledByCreateDatabase: false) { }
protected string GetMigrationHistory(DbMigrationsConfiguration migrationConfiguration, string migrationName) { // I would rather not use reflection to get the needed DbConnection but the alternative is requiring // more configuraton or hardcoding to SQL Server. This looks to be the lesser of multiple evils MigratorBase migrator = CreateMigrator(migrationConfiguration); MethodInfo method = migrator.GetType().GetMethod("CreateConnection", BindingFlags.NonPublic | BindingFlags.Instance); using (DbConnection dbConnection = (DbConnection)method.Invoke(migrator, null)) { dbConnection.Open(); using (HistoryContext historyContext = new HistoryContext(dbConnection, null)) { HistoryRow history = historyContext.History.SingleOrDefault(x => x.MigrationId == migrationName); if (history != null) { using (MemoryStream stream = new MemoryStream(history.Model)) { using (GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress)) { return XDocument.Load(gzip).ToString(); } } } else { return "Migration name not found"; } } } }