public static void Gerar(IAbstractDataContext dataContext) { if (dataContext == null) { throw new ArgumentNullException(nameof(dataContext)); } var types = MigrationAssembly .GetTypes(filtro: (f) => f.GetTabela() != null) .ToArray(); if (!MigracaoDatabase.IsGerarVersao(dataContext, types, out string versaoBase)) { return; } var migracao = dataContext.GetMigracao(); migracao.Clear(); types .ToList() .ForEach(type => migracao.CreateOrAlter(type)); migracao.DropForeigns(); migracao.CreateForeigns(); MigracaoDatabase.GravarVersao(dataContext, versaoBase); }
public virtual IEnumerable <Type> GetContextTypes() => ContextTool.GetContextTypes(_assembly) .Concat( MigrationAssembly.GetMigrationTypes(_assembly) .Select(MigrationAssembly.TryGetContextType) .Where(t => t != null)) .Distinct();
public virtual void BootstrapUsingEFProviderDdl(VersionedModel versionedModel) { DbConnection connection = (DbConnection)null; try { connection = this.CreateConnection(); using (HistoryContext context = this.CreateContext(connection, (string)null)) { context.Database.ExecuteSqlCommand(((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add(new HistoryRow() { MigrationId = MigrationAssembly.CreateMigrationId(Strings.InitialCreate).RestrictTo(this._migrationIdMaxLength), ContextKey = this._contextKey, Model = new ModelCompressor().Compress(versionedModel.Model), ProductVersion = versionedModel.Version ?? HistoryRepository._productVersion }); context.SaveChanges(); } } finally { this.DisposeConnection(connection); } }
public virtual void BuildDBContext(DbContextOptionsBuilder options) { var migrationsAssembly = MigrationAssembly.GetName().Name; var connectionString = GetConnectionString(); var dbServerEngine = GetDatabaseServerEngine(); switch (dbServerEngine) { case SupportedDatabaseServerEngines.MSSQL: options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)); break; case SupportedDatabaseServerEngines.PostgreSQL: options.UseNpgsql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)); break; case SupportedDatabaseServerEngines.MySQL: options.UseMySQL(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)); break; case SupportedDatabaseServerEngines.SQLite: options.UseSqlite(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)); break; case SupportedDatabaseServerEngines.None: default: break; } }
public void LaseVersionIsZeroIfNoMigrations() { Assembly assembly = GetType().Assembly; // загружаем текущую сборку - в ней нет миграций MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.AreEqual(0, migrationAssembly.LastVersion); }
public virtual void BootstrapUsingEFProviderDdl(XDocument model) { DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add( new HistoryRow { MigrationId = MigrationAssembly .CreateMigrationId(Strings.InitialCreate) .RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); context.SaveChanges(); } } finally { DisposeConnection(connection); } }
public Migrator( [NotNull] MigrationAssembly migrationAssembly, [NotNull] IHistoryRepository historyRepository, [NotNull] IDataStoreCreator dataStoreCreator, [NotNull] IMigrationSqlGenerator migrationSqlGenerator, [NotNull] SqlStatementExecutor executor, [NotNull] IRelationalConnection connection, [NotNull] IModelDiffer modelDiffer, [NotNull] IModel model, [NotNull] MigrationIdGenerator idGenerator, [NotNull] ISqlGenerator sqlGenerator) { Check.NotNull(migrationAssembly, nameof(migrationAssembly)); Check.NotNull(historyRepository, nameof(historyRepository)); Check.NotNull(dataStoreCreator, nameof(dataStoreCreator)); Check.NotNull(migrationSqlGenerator, nameof(migrationSqlGenerator)); Check.NotNull(executor, nameof(executor)); Check.NotNull(connection, nameof(connection)); Check.NotNull(modelDiffer, nameof(modelDiffer)); Check.NotNull(model, nameof(model)); Check.NotNull(idGenerator, nameof(idGenerator)); Check.NotNull(sqlGenerator, nameof(sqlGenerator)); _migrationAssembly = migrationAssembly; _historyRepository = historyRepository; _dataStoreCreator = (IRelationalDataStoreCreator)dataStoreCreator; _migrationSqlGenerator = migrationSqlGenerator; _executor = executor; _connection = connection; _modelDiffer = modelDiffer; _model = model; _idGenerator = idGenerator; _sqlGenerator = sqlGenerator; }
public void LastVersion() { Assembly assembly = Assembly.Load("ECM7.Migrator.TestAssembly"); MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.AreEqual(4, migrationAssembly.LastVersion); }
public MigrationScaffolder( [NotNull] DbContext context, [NotNull] IModel model, [NotNull] MigrationAssembly migrationAssembly, [NotNull] IModelDiffer modelDiffer, [NotNull] MigrationIdGenerator idGenerator, [NotNull] MigrationCodeGenerator migrationCodeGenerator, [NotNull] IHistoryRepository historyRepository, [NotNull] ILoggerFactory loggerFactory) { Check.NotNull(context, nameof(context)); Check.NotNull(model, nameof(model)); Check.NotNull(migrationAssembly, nameof(migrationAssembly)); Check.NotNull(modelDiffer, nameof(modelDiffer)); Check.NotNull(idGenerator, nameof(idGenerator)); Check.NotNull(migrationCodeGenerator, nameof(migrationCodeGenerator)); Check.NotNull(historyRepository, nameof(historyRepository)); Check.NotNull(loggerFactory, nameof(loggerFactory)); _contextType = context.GetType(); _model = model; _migrationAssembly = migrationAssembly; _modelDiffer = modelDiffer; _idGenerator = idGenerator; _migrationCodeGenerator = migrationCodeGenerator; _historyRepository = historyRepository; _logger = new LazyRef <ILogger>(loggerFactory.CreateLogger <MigrationScaffolder>); }
// Internal for testing protected internal virtual string GetNamespace( [CanBeNull] Migration lastMigration, [NotNull] string rootNamespace, [NotNull] Type contextType) { Check.NotEmpty(rootNamespace, "rootNamespace"); Check.NotNull(contextType, "contextType"); if (lastMigration != null) { return(lastMigration.GetType().Namespace); } var @namespace = rootNamespace + ".Migrations"; var existingMigrations = from t in MigrationAssembly.GetMigrationTypes(MigrationAssembly.Assembly) where t.Namespace == @namespace && MigrationAssembly.TryGetContextType(t) != contextType select t; if (existingMigrations.Any()) { return(@namespace + "." + contextType.Name); } return(@namespace); }
public void LastVersion() { Assembly assembly = GetType().GetTypeInfo().Assembly; MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.Equal(4, migrationAssembly.LatestVersion); }
public void ThrowIfNoMigrationForVersion() { Assembly assembly = Assembly.Load("ECM7.Migrator.TestAssembly"); MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.Throws <Exception>(() => migrationAssembly.GetMigrationInfo(99999999)); }
/// <summary> /// Инициализация /// </summary> public Migrator(ITransformationProvider provider, Assembly asm) { Require.IsNotNull(provider, "Не задан провайдер трансформации"); this.provider = provider; Require.IsNotNull(asm, "Не задана сборка с миграциями"); migrationAssembly = new MigrationAssembly(asm); }
public void LaseVersionIsZeroIfNoMigrations() { Assembly assembly = typeof(Migration).GetTypeInfo().Assembly; // ��������� ������� ������ - � ��� ��� �������� MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.Equal(0, migrationAssembly.LatestVersion); }
public void ThrowIfNoMigrationForVersion() { Assembly assembly = GetType().GetTypeInfo().Assembly; MigrationAssembly migrationAssembly = new MigrationAssembly(assembly); Assert.Throws <Exception>(() => migrationAssembly.GetMigrationInfo(99999999)); }
internal DbMigrator( DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase) : base((MigratorBase)null) { Check.NotNull <DbMigrationsConfiguration>(configuration, nameof(configuration)); Check.NotNull <Type>(configuration.ContextType, "configuration.ContextType"); this._configuration = configuration; this._calledByCreateDatabase = calledByCreateDatabase; this._existenceState = existenceState; if (usersContext != null) { this._usersContextInfo = new DbContextInfo(usersContext, (Func <IDbDependencyResolver>)null); } else { this._usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!this._usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible((object)configuration.ContextType); } } this._modelDiffer = this._configuration.ModelDiffer; DbContext context = usersContext ?? this._usersContextInfo.CreateInstance(); this._usersContext = context; try { this._migrationAssembly = new MigrationAssembly(this._configuration.MigrationsAssembly, this._configuration.MigrationsNamespace); this._currentModel = context.GetModel(); DbConnection connection = context.Database.Connection; this._providerFactory = DbProviderServices.GetProviderFactory(connection); this._defaultSchema = context.InternalContext.DefaultSchema ?? "dbo"; this._historyContextFactory = this._configuration.GetHistoryContextFactory(this._usersContextInfo.ConnectionProviderName); this._historyRepository = new HistoryRepository(context.InternalContext, this._usersContextInfo.ConnectionString, this._providerFactory, this._configuration.ContextKey, this._configuration.CommandTimeout, this._historyContextFactory, ((IEnumerable <string>) new string[1] { this._defaultSchema }).Concat <string>(this.GetHistorySchemas()), this._usersContext, this._existenceState); this._providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration.DependencyResolver.GetService <IManifestTokenResolver>().ResolveManifestToken(connection); DbModelBuilder modelBuilder = context.InternalContext.CodeFirstModel.CachedModelBuilder; this._modificationCommandTreeGenerator = new Lazy <ModificationCommandTreeGenerator>((Func <ModificationCommandTreeGenerator>)(() => new ModificationCommandTreeGenerator(modelBuilder.BuildDynamicUpdateModel(new DbProviderInfo(this._usersContextInfo.ConnectionProviderName, this._providerManifestToken)), this.CreateConnection()))); DbInterceptionContext interceptionContext = new DbInterceptionContext().WithDbContext(this._usersContext); this._targetDatabase = Strings.LoggingTargetDatabaseFormat((object)DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext), (object)DbInterception.Dispatch.Connection.GetDatabase(connection, interceptionContext), (object)this._usersContextInfo.ConnectionProviderName, this._usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? (object)Strings.LoggingExplicit : (object)this._usersContextInfo.ConnectionStringOrigin.ToString()); this._legacyContextKey = context.InternalContext.DefaultContextKey; this._emptyModel = this.GetEmptyModel(); } finally { if (usersContext == null) { this._usersContext = (DbContext)null; context.Dispose(); } } }
public void Create_migration_assembly() { using (var context = new Context()) { var migrationAssembly = new MigrationAssembly(context.Configuration); Assert.Equal("EntityFramework.Migrations.Tests", migrationAssembly.Assembly.GetName().Name); } }
public void Create_migration_assembly() { using (var context = new Context()) { var migrationAssembly = new MigrationAssembly(context.Configuration); Assert.Equal("Microsoft.Data.Entity.Migrations.Tests", migrationAssembly.Assembly.GetName().Name); Assert.Equal("Microsoft.Data.Entity.Migrations.Tests.Infrastructure.Migrations", migrationAssembly.Namespace); } }
public void ForNullProviderShouldThrowException() { Assembly assembly = GetType().GetTypeInfo().Assembly; var loader = new MigrationAssembly(assembly); var mi = loader.GetMigrationInfo(1); Assert.Throws <ArgumentNullException>(() => loader.InstantiateMigration(mi, null)); }
public void ForNullProviderShouldThrowException() { Assembly assembly = Assembly.Load("ECM7.Migrator.TestAssembly"); var loader = new MigrationAssembly(assembly); var mi = loader.GetMigrationInfo(1); Assert.Throws <Exception>(() => loader.InstantiateMigration(mi, null)); }
internal override void Upgrade( IEnumerable <string> pendingMigrations, string targetMigrationId, string lastMigrationId) { DbMigration lastMigration = null; if (lastMigrationId != null) { lastMigration = _migrationAssembly.GetMigration(lastMigrationId); } foreach (var pendingMigration in pendingMigrations) { var migration = _migrationAssembly.GetMigration(pendingMigration); base.ApplyMigration(migration, lastMigration); lastMigration = migration; _emptyMigrationNeeded = false; if (pendingMigration.EqualsIgnoreCase(targetMigrationId)) { break; } } if (string.IsNullOrWhiteSpace(targetMigrationId) && ((_emptyMigrationNeeded && _configuration.AutomaticMigrationsEnabled) || IsModelOutOfDate(_currentModel, lastMigration))) { if (!_configuration.AutomaticMigrationsEnabled) { throw Error.AutomaticDisabledException(); } base.AutoMigrate( MigrationAssembly.CreateMigrationId( _calledByCreateDatabase ? Strings.InitialCreate : Strings.AutomaticMigration), _calledByCreateDatabase ? _emptyModel.Value : GetLastModel(lastMigration), _currentModel, false); } // Context may not be constructable when Migrations is being called by DbContext CreateDatabase // and the config cannot have Seed data anyway, so avoid doing model diff and creating the context to seed. if (!_calledByCreateDatabase && !IsModelOutOfDate(_currentModel, lastMigration)) { base.SeedDatabase(); } }
public void CheckForDuplicatedVersion() { var versions = new long[] { 1, 2, 3, 4, 2, 4 }; var ex = Assert.Throws <DuplicatedVersionException>(() => MigrationAssembly.CheckForDuplicatedVersion(versions)); Assert.AreEqual(2, ex.Versions.Count); Assert.That(ex.Versions.Contains(2)); Assert.That(ex.Versions.Contains(4)); }
public void Loads_and_cache_model_snapshot() { using (var context = new Context()) { var migrationAssembly = new MigrationAssembly(context.Configuration); var model1 = migrationAssembly.Model; var model2 = migrationAssembly.Model; Assert.Same(model1, model2); } }
internal override void Upgrade( IEnumerable <string> pendingMigrations, string targetMigrationId, string lastMigrationId) { DbMigration lastMigration = null; if (lastMigrationId != null) { lastMigration = _migrationAssembly.GetMigration(lastMigrationId); } foreach (var pendingMigration in pendingMigrations) { var migration = _migrationAssembly.GetMigration(pendingMigration); base.ApplyMigration(migration, lastMigration); lastMigration = migration; _emptyMigrationNeeded = false; if (pendingMigration.EqualsIgnoreCase(targetMigrationId)) { break; } } if (string.IsNullOrWhiteSpace(targetMigrationId) && ((_emptyMigrationNeeded && _configuration.AutomaticMigrationsEnabled) || IsModelOutOfDate(_currentModel, lastMigration))) { if (!_configuration.AutomaticMigrationsEnabled) { throw Error.AutomaticDisabledException(); } base.AutoMigrate( MigrationAssembly.CreateMigrationId( _calledByCreateDatabase ? Strings.InitialCreate : Strings.AutomaticMigration), _calledByCreateDatabase ? _emptyModel.Value : GetLastModel(lastMigration), _currentModel, false); } if (!IsModelOutOfDate(_currentModel, lastMigration)) { base.SeedDatabase(); } }
internal DbMigrator( DbContext usersContext = null, DbProviderFactory providerFactory = null, MigrationAssembly migrationAssembly = null) : base((MigratorBase)null) { this._usersContext = usersContext; this._providerFactory = providerFactory; this._migrationAssembly = migrationAssembly; this._usersContextInfo = new DbContextInfo(typeof(DbContext)); this._configuration = new DbMigrationsConfiguration(); this._calledByCreateDatabase = true; }
/// <summary> /// Записывает в лог список миграций /// </summary> /// <param name="asm">Сборка с миграциями</param> public void WriteMigrationAssemblyInfo(MigrationAssembly asm) { Info($"Migration key: {asm.Key}"); var msg = new StringBuilder("Loaded migrations:").AppendLine(); foreach (var mi in asm.MigrationsTypes) { msg.AppendLine($"{mi.Version.ToString().PadLeft(5)} {mi.Type.Name.ToHumanName()}"); } Trace(msg.ToString()); }
// <summary> // For testing. // </summary> internal DbMigrator( DbContext usersContext = null, DbProviderFactory providerFactory = null, MigrationAssembly migrationAssembly = null) : base(null) { _contextForInterception = usersContext; _providerFactory = providerFactory; _migrationAssembly = migrationAssembly; _usersContextInfo = new DbContextInfo(typeof(DbContext)); _configuration = new DbMigrationsConfiguration(); _calledByCreateDatabase = true; }
/// <summary> /// ������������� /// </summary> public Migrator(ITransformationProvider provider, Assembly asm, ILogger logger = null) { if (asm == null) { throw new ArgumentNullException(nameof(asm)); } Provider = provider ?? throw new ArgumentNullException(nameof(provider)); Logger = new MigrationLogger(logger); migrationAssembly = new MigrationAssembly(asm); Logger.WriteMigrationAssemblyInfo(migrationAssembly); }
public void CanLoadMigrationsWithKey() { Assembly assembly = Assembly.Load("ECM7.Migrator.TestAssembly"); var migrationAssembly = new MigrationAssembly(assembly); IList <long> list = migrationAssembly.MigrationsTypes.Select(x => x.Version).ToList(); Assert.AreEqual("test-key111", migrationAssembly.Key); Assert.AreEqual(3, list.Count); Assert.IsTrue(list.Contains(1)); Assert.IsTrue(list.Contains(2)); Assert.IsTrue(list.Contains(4)); }
/// <summary> /// Initialize MigrationCallingName and MigrationAssembly from <paramref name="model"/> /// </summary> /// <param name="model"></param> protected void InitMetadata(IMigrationModel model) { if (model == null) { return; } MigrationAssembly = model.GetType().Assembly; if (MigrationCallingNameConfigField.IsEmpty()) { MigrationName = MigrationAssembly.GetName().Name; } }