Exemple #1
0
        public void Can_update_generate_update_when_empty_target_database()
        {
            ResetDatabase();

            CreateMigrator <ShopContext_v1>().Update();

            Assert.True(TableExists("MigrationsProducts"));

            var migrator = CreateMigrator <ShopContext_v2>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration");

            migrator = CreateMigrator <ShopContext_v2>(false, scaffoldedMigrations: generatedMigration);

            migrator.Update();

            Assert.True(TableExists("crm.tbl_customers"));
        }
Exemple #2
0
        public void AddMigrations(int i)
        {
            var config     = new DataMigrations();
            var scaffolder = new MigrationScaffolder(config);
            var migration  = scaffolder.Scaffold("Migration" + i);

            File.WriteAllText("Migrations/" + migration.MigrationId + ".cs", migration.UserCode);

            File.WriteAllText("Migrations/" + migration.MigrationId + ".Designer.cs", migration.DesignerCode);

            using (var writer = new ResXResourceWriter("Migrations/" + migration.MigrationId + ".resx"))
            {
                foreach (var resource in migration.Resources)
                {
                    writer.AddResource(resource.Key, resource.Value);
                }
            }
        }
Exemple #3
0
        public void Update_when_new_earlier_migration_should_throw_auto_disabled_exception()
        {
            ResetDatabase();

            var migratorA = CreateMigrator <MultiUserContextA>();
            var m1        = new MigrationScaffolder(migratorA.Configuration).Scaffold("M1");

            var migratorB = CreateMigrator <MultiUserContextB>();
            var m2        = new MigrationScaffolder(migratorB.Configuration).Scaffold("M2");

            CreateMigrator <MultiUserContextB>(scaffoldedMigrations: m2).Update();

            Assert.Throws <AutomaticMigrationsDisabledException>(
                () => CreateMigrator <MultiUserContextAB>(
                    scaffoldedMigrations: new[] { m1, m2 },
                    automaticMigrationsEnabled: false)
                .Update());
        }
Exemple #4
0
        static void addMigration(string[] args)
        {
            var config     = new Configuration();
            var scaffolder = new MigrationScaffolder(config);
            var migration  = scaffolder.Scaffold(args[1]);

            File.WriteAllText(Path.Combine(args[2], migration.MigrationId + ".cs"), migration.UserCode);

            File.WriteAllText(Path.Combine(args[2], migration.MigrationId + ".Designer.cs"), migration.DesignerCode);

            using (var writer = new ResXResourceWriter(Path.Combine(args[2], migration.MigrationId + ".resx")))
            {
                foreach (var resource in migration.Resources)
                {
                    writer.AddResource(resource.Key, resource.Value);
                }
            }
        }
Exemple #5
0
        public void Can_update_multiple_migrations_having_a_trailing_automatic_migration()
        {
            ResetDatabase();

            CreateMigrator <ShopContext_v2>().Update();

            var migrator = CreateMigrator <ShopContext_v3>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Version 2");

            ResetDatabase();

            CreateMigrator <ShopContext_v6>(
                automaticDataLossEnabled: true,
                scaffoldedMigrations: generatedMigration).Update();

            Assert.True(TableExists("MigrationsStores"));
        }
        public virtual ScaffoldedMigration CreateMigration(
            [NotNull] string migrationName,
            [NotNull] string rootNamespace,
            [CanBeNull] string contextTypeName)
        {
            Check.NotEmpty(migrationName, "migrationName");
            Check.NotEmpty(rootNamespace, "rootNamespace");

            var contextType = GetContextType(contextTypeName);

            using (var context = CreateContext(contextType))
            {
                var configuration = context.Configuration;

                var extension = RelationalOptionsExtension.Extract(configuration);
                if (extension.MigrationNamespace == null)
                {
                    extension.MigrationNamespace = rootNamespace + ".Migrations";
                }

                var serviceProvider = configuration.Services.ServiceProvider;
                var scaffolder      = new MigrationScaffolder(
                    configuration,
                    serviceProvider.GetService <MigrationAssembly>(),
                    serviceProvider.GetService <ModelDiffer>(),
                    new CSharpMigrationCodeGenerator(new CSharpModelCodeGenerator()));

                var migration = scaffolder.ScaffoldMigration(migrationName);

                // Derive default directory from namespace
                if (migration.Directory == null)
                {
                    var directory = migration.MigrationNamespace;
                    if (directory.StartsWith(rootNamespace + '.'))
                    {
                        directory = directory.Substring(rootNamespace.Length + 1);
                    }

                    migration.Directory = directory.Replace('.', Path.DirectorySeparatorChar);
                }

                return(migration);
            }
        }
Exemple #7
0
        public void Can_upgrade_from_5_and_existing_code_auto_migrations_still_work()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            migrator.Update();

            // create v5 history rows

            using (var context = CreateContext <ShopContext_v1>())
            {
                ExecuteOperations(
                    new MigrationOperation[]
                {
                    GetDropHistoryTableOperation(),
                    GetCreateHistoryTableOperation(),
                    CreateInsertOperation("MyKey", "201112202056275_NoHistoryModelAutomaticMigration", GetModel(context))
                });
            }

            migrator = CreateMigrator <ShopContext_v2>();

            var scaffoldedMigration
                = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration_v2");

            ResetDatabase();

            migrator
                = CreateMigrator <ShopContext_v2>(
                      scaffoldedMigrations: scaffoldedMigration,
                      automaticDataLossEnabled: true);

            migrator.Update();

            Assert.True(TableExists("crm.tbl_customers"));
            Assert.True(TableExists("dbo." + HistoryContext.DefaultTableName));

            migrator.Update("0");

            Assert.False(TableExists("crm.tbl_customers"));
            Assert.False(TableExists("dbo." + HistoryContext.DefaultTableName));
        }
Exemple #8
0
        public void MigrationScaffolderDetectsRequiredChanges(IFixture fixture, IServiceProvider serviceProvider, ObjectRepository sut, Signature signature, string message)
        {
            // Arrange
            var repositoryDescription = RepositoryFixture.GetRepositoryDescription();

            sut.SaveInNewRepository(signature, message, repositoryDescription);
            var updated = sut.With(i => i.Migrations.Add(fixture.Create <Migration>()));
            var commit  = sut.Commit(updated, signature, message);

            // Act
            var migrationScaffolder = new MigrationScaffolder(serviceProvider, repositoryDescription);
            var migrators           = migrationScaffolder.Scaffold(sut.CommitId, commit, MigrationMode.Upgrade);

            // Assert
            Assert.That(migrators, Has.Count.EqualTo(1));
            Assert.That(migrators[0].CommitId, Is.EqualTo(commit));
            Assert.That(migrators[0].Mode, Is.EqualTo(MigrationMode.Upgrade));
            Assert.That(migrators[0].Migrations, Has.Count.EqualTo(1));
        }
Exemple #9
0
        public void Upgrade_from_earlier_version_should_upgrade_history_table_when_updating_generated()
        {
            ResetDatabase();

            var createTableOperations = GetLegacyHistoryCreateTableOperations();

            ExecuteOperations(
                createTableOperations.Concat(
                    new[]
            {
                new SqlOperation(
                    @"INSERT INTO [__MigrationHistory] ([MigrationId], [CreatedOn], [Model]) 
                                  VALUES ('000000000000000_ExistingMigration', GETDATE(), 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF54AD7E074A10880601324D8904010ECC188CDE692EC1D69472329AB2A81CA6556655D661640CCED9DBCF7DE7BEFBDF7DE7BEFBDF7BA3B9D4E27F7DFFF3F5C6664016CF6CE4ADAC99E2180AAC81F3F7E7C1F3F22FEC7BFF71F7CFC7BBC5B94E9655E3745B5FCECA3DDF1CE4769BE9C56B36279F1D947EBF67CFBE0A3DFE3E8374E1E9FCE16EFD29F34EDF6D08EDE5C369F7D346FDBD5A3BB779BE93C5F64CD78514CEBAAA9CEDBF1B45ADCCD66D5DDBD9D9D83BBBB3B777302F111C14AD3C7AFD6CBB658E4FC07FD79522DA7F9AA5D67E517D52C2F1BFD9CBE79CD50D317D9226F56D934FFEC236ADB54657EBC5A95C5346B099DDD8FD2E3B2C80895D77979FE9E78ED3C045E1FD91EA9CF53C2ADBDA67EDAAC58E63577CEFDB6F9BBF6A3F4AEC3EEAEA067867177601C8FBFC8562B22A8372EFD247DAD83DA7EFDFE782F04C6DD69B3097DDB535BD5D945DEF916E39AE5CF8ABA699F666D36C99AFCA3F464B688348B0C5F61DBF177C6F958FBBCCDA4769090261FA52FEBEAB2980181D7D74D9B2FC668307EFD8BCA93B2C897AD6BF045B62CCEF3A67D53BDCDC1A044A3AFCF160FEFEEEC812DEE36CDACBC156FF468B8814BFA54797CD71788C74FF3A6B820E89E782CF32958DD01356DCE96E715D16095D7EDF5EBBCF571354DCCD78AEC17799BCD08CFE3BA2DCEB3694B5F4FF3A6A179FB28FDC9AC5C5393D3C5249F9D2DBF5CB7AB757BDC34F962525E8763DADC3F8B4288F3E32F57F8CB6383AF3F0442B3A021E45F2E9FAC8B7266F17E969521ED874160CA3ECFE9735621AF5BFA995F5C5B482FAAE52D0129F99EE6AB7C3923967C932F5625016BBE5CBECE2EF361DC6EA66148B1C74F8BECA2CE163E05E513C5E475463D7B5D5007FE1BAE3FFAF3F15D28F4A3FF270000FFFF4817137F02060000)")
            }).ToArray());

            var migrator = CreateMigrator <ShopContext_v1>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration1");

            migrator = CreateMigrator <ShopContext_v1>(
                automaticMigrationsEnabled: false,
                scaffoldedMigrations: new[] { generatedMigration });

            Assert.False(ColumnExists(HistoryContext.DefaultTableName, "ProductVersion"));
            Assert.False(ColumnExists(HistoryContext.DefaultTableName, "ContextKey"));
            Assert.True(ColumnExists(HistoryContext.DefaultTableName, "Hash"));
            Assert.True(ColumnExists(HistoryContext.DefaultTableName, "CreatedOn"));

            migrator.Update(generatedMigration.MigrationId);

            Assert.True(ColumnExists(HistoryContext.DefaultTableName, "ProductVersion"));
            Assert.True(ColumnExists(HistoryContext.DefaultTableName, "ContextKey"));
            Assert.False(ColumnExists(HistoryContext.DefaultTableName, "Hash"));
            Assert.False(ColumnExists(HistoryContext.DefaultTableName, "CreatedOn"));

            if (ProviderInfo.ProviderInvariantName == "System.Data.SqlClient")
            {
                Assert.Equal(0, GetColumnIndex(HistoryContext.DefaultTableName, "MigrationId"));
                Assert.Equal(1, GetColumnIndex(HistoryContext.DefaultTableName, "ContextKey"));
                Assert.Equal(2, GetColumnIndex(HistoryContext.DefaultTableName, "Model"));
                Assert.Equal(3, GetColumnIndex(HistoryContext.DefaultTableName, "ProductVersion"));
            }
        }
        public void Auto_migration_when_functions_and_model_not_current_should_throw()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            migrator.Update();

            migrator = CreateMigrator <ShopContext_v2>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration");

            migrator = CreateMigrator <ShopContext_v2>(scaffoldedMigrations: generatedMigration);

            ResetDatabase();

            Assert.Throws <MigrationsException>(() => migrator.Update())
            .ValidateMessage("AutomaticStaleFunctions");
        }
Exemple #11
0
        public void Can_explicit_update_after_explicit_update_when_custom_history_factory()
        {
            ResetDatabase();

            var migrator
                = CreateMigrator <ShopContext_v1>(historyContextFactory: _testHistoryContextFactoryA);

            var generatedMigrationA
                = new MigrationScaffolder(migrator.Configuration)
                  .Scaffold("Migration_v1");

            migrator
                = CreateMigrator <ShopContext_v1>(
                      automaticMigrationsEnabled: false,
                      historyContextFactory: _testHistoryContextFactoryA,
                      scaffoldedMigrations: generatedMigrationA);

            migrator.Update();

            Assert.True(TableExists("dbo.OrderLines"));
            Assert.True(TableExists("__Migrations"));

            var generatedMigrationB
                = new MigrationScaffolder(migrator.Configuration)
                  .Scaffold("Migration_v2");

            migrator
                = CreateMigrator <ShopContext_v2>(
                      automaticDataLossEnabled: true,
                      historyContextFactory: _testHistoryContextFactoryA,
                      scaffoldedMigrations: new[] { generatedMigrationA, generatedMigrationB });

            migrator.Update();

            Assert.True(TableExists("crm.tbl_customers"));

            migrator.Update("0");

            Assert.False(TableExists("crm.tbl_customers"));
            Assert.False(TableExists("dbo.OrderLines"));
            Assert.False(TableExists("__Migrations"));
        }
Exemple #12
0
        public void Can_scaffold_on_ce_and_run_on_sql()
        {
            DatabaseProvider = DatabaseProvider.SqlServerCe;

            ResetDatabase();

            var migrator = CreateMigrator <CrossProviderContext_v1>();

            var scaffoldedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration");

            DatabaseProvider = DatabaseProvider.SqlClient;

            ResetDatabase();

            migrator = CreateMigrator <CrossProviderContext_v1>(scaffoldedMigrations: scaffoldedMigration);

            migrator.Update();

            Assert.True(TableExists("MigrationsProducts"));
        }
        public void ScaffoldInitialCreate_should_return_scaffolded_migration_when_db_initialized_and_schema_specified()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v5>();

            var initialCreate = new MigrationScaffolder(migrator.Configuration).Scaffold("InitialCreate");

            migrator = CreateMigrator <ShopContext_v5>(scaffoldedMigrations: initialCreate, contextKey: typeof(ShopContext_v5).FullName);

            migrator.Update();

            migrator = CreateMigrator <ShopContext_v5>(contextKey: "NewOne");

            var scaffoldedMigration = migrator.ScaffoldInitialCreate("Foo");

            Assert.NotNull(scaffoldedMigration);
            Assert.NotSame(initialCreate, scaffoldedMigration);
            Assert.Equal(initialCreate.MigrationId, scaffoldedMigration.MigrationId);
        }
        public void Update_when_target_migration_id_valid_should_migrate_to_target_version()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            var generatedMigration1 = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration1");

            migrator = CreateMigrator <ShopContext_v2>();

            var generatedMigration2 = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration2");

            migrator = CreateMigrator <ShopContext_v2>(
                automaticMigrationsEnabled: false,
                scaffoldedMigrations: new[] { generatedMigration1, generatedMigration2 });

            migrator.Update(generatedMigration1.MigrationId);

            Assert.True(TableExists("MigrationsCustomers"));
        }
        public void Generate_should_emit_null_source_when_last_migration_was_explicit()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration1");

            migrator = CreateMigrator <ShopContext_v1>(scaffoldedMigrations: generatedMigration);

            migrator.Update();

            migrator = CreateMigrator <ShopContext_v2>();

            generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration2");

            Assert.True(
                generatedMigration.DesignerCode.Contains("return null") ||
                generatedMigration.DesignerCode.Contains("Return Nothing"));
        }
        public void VerifyDatabaseIsCompatibleWithModel()
        {
            // Arrange
            var context = new MyDbContext();
            // Act
            var isCompatible = context.Database.CompatibleWithModel(false);

            // Visual Assertion
            if (!isCompatible)
            {
                var config           = new MyDbMigrationsConfiguration();
                var scaffolder       = new MigrationScaffolder(config);
                var pendingMigration = scaffolder.Scaffold("MissingMigration");
                Trace.WriteLine("Missing Migration:");
                Trace.WriteLine("");
                Trace.WriteLine(pendingMigration.UserCode);
            }
            // Assert
            Assert.IsTrue(isCompatible, "The EF model is not compatible with the database. An EF migration needs to be created. See output for sample of missing migration.");
        }
Exemple #17
0
        private static void GenerateDbMigration(string className)
        {
            Console.Write("Generating migration class......");

            var config     = new Configuration();
            var scaffolder = new MigrationScaffolder(config);
            var migration  = scaffolder.Scaffold(className);

            File.WriteAllText(migration.MigrationId + ".cs", migration.UserCode);
            File.WriteAllText(migration.MigrationId + ".Designer.cs", migration.DesignerCode);
            using (var writer = new ResXResourceWriter(migration.MigrationId + ".resx"))
            {
                foreach (var resource in migration.Resources)
                {
                    writer.AddResource(resource.Key, resource.Value);
                }
            }

            Console.Write("OK\n");
        }
        public void Can_generate_migration_from_user_code()
        {
            var migrator
                = new DbMigrator(
                      new DbMigrationsConfiguration
            {
                ContextType         = typeof(ShopContext_v1),
                MigrationsAssembly  = SystemComponentModelDataAnnotationsAssembly,
                MigrationsNamespace = "Foo",
                MigrationsDirectory = "Bar"
            });

            var migration = new MigrationScaffolder(migrator.Configuration).Scaffold("Test");

            Assert.False(string.IsNullOrWhiteSpace(migration.DesignerCode));
            Assert.False(string.IsNullOrWhiteSpace(migration.Language));
            Assert.False(string.IsNullOrWhiteSpace(migration.MigrationId));
            Assert.False(string.IsNullOrWhiteSpace(migration.UserCode));
            Assert.False(string.IsNullOrWhiteSpace(migration.Directory));
        }
Exemple #19
0
        public void Generated()
        {
            ResetDatabaseToV1();

            var migrator
                = CreateMigrator <TContextV2>(scaffoldedMigrations: _generatedMigration_v1);

            var generatedMigration_v2
                = new MigrationScaffolder(migrator.Configuration).Scaffold("V2");

            var migrationsConfiguration
                = CreateMigrationsConfiguration <TContextV2>(
                      scaffoldedMigrations: new[] { _generatedMigration_v1, generatedMigration_v2 });

            migrationsConfiguration.SetSqlGenerator(DbProviders.Sql, _upVerifier);
            migrationsConfiguration.SetSqlGenerator(DbProviders.SqlCe, _upVerifier);

            new DbMigrator(migrationsConfiguration).Update();

            // Bring up via generated
            CreateMigrator <TContextV2>(
                scaffoldedMigrations: new[] { _generatedMigration_v1, generatedMigration_v2 })
            .Update();

            migrationsConfiguration
                = CreateMigrationsConfiguration <TContextV2>(
                      scaffoldedMigrations: new[] { _generatedMigration_v1, generatedMigration_v2 });

            migrationsConfiguration.SetSqlGenerator(DbProviders.Sql, _downVerifier);
            migrationsConfiguration.SetSqlGenerator(DbProviders.SqlCe, _downVerifier);

            try
            {
                new DbMigrator(migrationsConfiguration)
                .Update(_generatedMigration_v1.MigrationId);
            }
            catch (NotSupportedException)
            {
                Assert.True(IsDownNotSupported);
            }
        }
Exemple #20
0
        public async Task NoPendingMigrations(string dbName, string argumentName, MigrationContextFactory factory, IServiceProvider serviceProvider)
        {
            _dbName = dbName;

            var migrationContext = await factory.CreateMigrationContextAsync(argumentName, serviceProvider);

            var dbMigrator = migrationContext.GetDbMigrator();
            var migrations = dbMigrator.GetLocalMigrations();

            dbMigrator.Update(migrations.Last());

            var migrationScaffolder = new MigrationScaffolder(dbMigrator.Configuration);

            var migrationName = $"TestMigration{DateTimeOffset.UtcNow:yyyyMMddHHmmssFFFFFFF}";
            var result        = migrationScaffolder.Scaffold(migrationName);

            _output.WriteLine("Migration content:");
            _output.WriteLine(new string('-', 60));
            _output.WriteLine(result.UserCode);
            _output.WriteLine(new string('-', 60));

            Assert.Equal(
                $@"namespace {dbMigrator.Configuration.MigrationsNamespace}
{{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class {migrationName} : DbMigration
    {{
        public override void Up()
        {{
        }}
        
        public override void Down()
        {{
        }}
    }}
}}
", result.UserCode);
        }
        public void Update_down_when_initial_version_and_no_database_should_be_noop()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration1");

            migrator = CreateMigrator <ShopContext_v1>(
                automaticMigrationsEnabled: false,
                scaffoldedMigrations: generatedMigration);

            migrator.Update();

            Assert.True(TableExists("MigrationsCustomers"));

            DropDatabase();

            migrator.Update(DbMigrator.InitialDatabase);

            Assert.False(migrator.GetDatabaseMigrations().Any());
        }
Exemple #22
0
        public void Update_down_when_explicit_should_migrate_to_target_version()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            var generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration1");

            migrator = CreateMigrator <ShopContext_v1>(
                automaticMigrationsEnabled: false,
                scaffoldedMigrations: generatedMigration);

            migrator.Update();

            Assert.True(TableExists("MigrationsCustomers"));

            migrator.Update(DbMigrator.InitialDatabase);

            Assert.False(TableExists("MigrationsCustomers"));

            AssertHistoryContextDoesNotExist();
        }
        public void Can_script_pending_migrations()
        {
            ResetDatabase();

            var migrator1 = CreateMigrator <ShopContext_v1>();
            var version1  = new MigrationScaffolder(migrator1.Configuration).Scaffold("Version1");

            CreateMigrator <ShopContext_v1>(scaffoldedMigrations: version1).Update();

            var migrator2 = CreateMigrator <ShopContext_v2>(scaffoldedMigrations: version1);

            var version2 = new MigrationScaffolder(migrator2.Configuration).Scaffold("Version2");

            var migrator3          = CreateMigrator <ShopContext_v2>(scaffoldedMigrations: new[] { version1, version2 });
            var scriptingDecorator = new MigratorScriptingDecorator(migrator3);

            var script = scriptingDecorator.ScriptUpdate(null, null);

            Assert.False(script.Contains("Version1"));
            Assert.True(script.Contains("Version2"));
            Assert.False(script.Contains("AutomaticMigration"));
        }
Exemple #24
0
        public void AddMigration(string name, bool ignoreChanges)
        {
            var config = FindDbMigrationsConfiguration();

            // Scaffold migration.
            var scaffolder = new MigrationScaffolder(config);
            var migration  = scaffolder.Scaffold(name, ignoreChanges);

            // Write the user code file.
            File.WriteAllText(Combine(MigrationsDir, migration.MigrationId + ".cs"), migration.UserCode);

            // Write needed resource values directly inside the designer code file.
            // Apparently, aspnet and resource files don't play well (or more specifically,
            // the way ef6 migration generator is interacting with the resources system)
            var targetValue  = migration.Resources["Target"];
            var designerCode = migration.DesignerCode
                               .Replace("Resources.GetString(\"Target\")", $"\"{targetValue}\"")
                               .Replace("private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate));", "");

            // Write the designer code file.
            File.WriteAllText(Path.Combine(MigrationsDir, migration.MigrationId + ".Designer.cs"), designerCode);
        }
Exemple #25
0
        public virtual void AddMigration(
            String migrationName,
            String contextTypeName,
            String rootNamespace,
            String projectDir)
        {
            var contextType       = GetContextType(contextTypeName);
            var configurationType = GetConfigurationType(contextType);

            var configuration = CreateConfiguration(configurationType);
            var scaffolder    = new MigrationScaffolder(configuration);

            var migration = scaffolder.Scaffold(migrationName);

            var migrationDirectory    = Path.Combine(projectDir, migration.Directory);
            var migrationFile         = Path.Combine(migrationDirectory, migration.MigrationId + "." + migration.Language);
            var migrationMetadataFile = Path.Combine(migrationDirectory, migration.MigrationId + ".Designer." + migration.Language);

            var designerCode =
                migration.DesignerCode
                .Replace("private readonly ResourceManager", "//private readonly ResourceManager");

            foreach (var replaceKey in new[] { "Source", "Target" })
            {
                if (migration.Resources.ContainsKey(replaceKey))
                {
                    var code = String.Format("Resources.GetString(\"{0}\")", replaceKey);

                    var valueString = String.Format("\"{0}\"", migration.Resources[replaceKey]);

                    designerCode = designerCode.Replace(code, valueString);
                }
            }

            Directory.CreateDirectory(migrationDirectory);
            File.WriteAllText(migrationFile, migration.UserCode);
            File.WriteAllText(migrationMetadataFile, designerCode);
        }
        public static MigrationInfo CreateMigrations(string migrationName, string migrationDirectory, Func <string, IResourceWriter> createResourceWriter)
        {
            var configuration = new Configuration();
            var scaffolder    = new MigrationScaffolder(configuration);
            var migration     = scaffolder.Scaffold(migrationName);

            var codeFileName     = migration.MigrationId + ".cs";
            var designerFileName = migration.MigrationId + ".Designer.cs";
            var resourceFileName = migration.MigrationId + ".resx";

            File.WriteAllText($"{migrationDirectory}/{codeFileName}", migration.UserCode);
            File.WriteAllText($"{migrationDirectory}/{designerFileName}", migration.DesignerCode);

            using (var resourceWriter = createResourceWriter($"{migrationDirectory}/{resourceFileName}"))
            {
                foreach (var resource in migration.Resources)
                {
                    resourceWriter.AddResource(resource.Key, resource.Value);
                }
            }

            return(new MigrationInfo(codeFileName, designerFileName, resourceFileName));
        }
Exemple #27
0
        public void Can_use_per_provider_factory()
        {
            ResetDatabase();

            try
            {
                MutableResolver.AddResolver <Func <DbConnection, string, HistoryContext> >(_ => _testHistoryContextFactoryA);

                var migrator = CreateMigrator <ShopContext_v1>();

                var generatedMigration
                    = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration");

                migrator
                    = CreateMigrator <ShopContext_v1>(
                          automaticMigrationsEnabled: false,
                          scaffoldedMigrations: generatedMigration);

                migrator.Update();

                Assert.True(TableExists("MigrationsCustomers"));
                Assert.True(TableExists("__Migrations"));

                migrator.Update("0");

                Assert.False(TableExists("MigrationsCustomers"));
                Assert.False(TableExists("__Migrations"));

                var historyRepository = new HistoryRepository(ConnectionString, ProviderFactory, "MyKey", null);

                Assert.Null(historyRepository.GetLastModel());
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
Exemple #28
0
        public void Update_blocks_automatic_migration_when_explicit_source_model()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1>();

            migrator.Update();

            migrator = CreateMigrator <ShopContext_v2>(automaticDataLossEnabled: true);

            migrator.Update();

            string migrationName      = "Migration1";
            var    generatedMigration = new MigrationScaffolder(migrator.Configuration).Scaffold(migrationName);

            ResetDatabase();

            migrator = CreateMigrator <ShopContext_v1>();

            migrator.Update();

            // Fix-up migrationId to come after previous automatic migration
            var oldMigrationId = generatedMigration.MigrationId;
            var newMigrationId = GenerateUniqueMigrationName(migrationName);

            generatedMigration.MigrationId  = newMigrationId;
            generatedMigration.DesignerCode = generatedMigration.DesignerCode.Replace(oldMigrationId, newMigrationId);

            migrator
                = CreateMigrator <ShopContext_v2>(
                      automaticMigrationsEnabled: false,
                      automaticDataLossEnabled: false,
                      scaffoldedMigrations: generatedMigration);

            Assert.Throws <AutomaticDataLossException>(() => migrator.Update())
            .ValidateMessage("AutomaticDataLoss");
        }
Exemple #29
0
        public void Can_update_when_explicit_migrations()
        {
            ResetDatabase();

            var migratorA = CreateMigrator <ContextA>();

            var generatedMigrationA = new MigrationScaffolder(migratorA.Configuration).Scaffold("MigrationA");

            migratorA
                = CreateMigrator <ContextA>(
                      contextKey: "KeyA",
                      automaticMigrationsEnabled: false,
                      scaffoldedMigrations: generatedMigrationA);

            migratorA.Update();

            var migratorB = CreateMigrator <ContextB>();

            var generatedMigrationB = new MigrationScaffolder(migratorB.Configuration).Scaffold("MigrationB");

            migratorB
                = CreateMigrator <ContextB>(
                      contextKey: "KeyB",
                      automaticMigrationsEnabled: false,
                      scaffoldedMigrations: generatedMigrationB);

            migratorB.Update();

            Assert.True(TableExists("TenantAs"));
            Assert.True(TableExists("TenantBs"));

            migratorA.Update("0");
            migratorB.Update("0");

            Assert.False(TableExists("TenantAs"));
            Assert.False(TableExists("TenantBs"));
        }
        public void ScaffoldInitialCreate_should_return_scaffolded_migration_when_db_initialized()
        {
            ResetDatabase();

            var migrator = CreateMigrator <ShopContext_v1b>();

            var initialCreate = new MigrationScaffolder(migrator.Configuration).Scaffold("InitialCreate");

            migrator = CreateMigrator <ShopContext_v1b>(scaffoldedMigrations: initialCreate, contextKey: typeof(ShopContext_v1b).FullName);

            migrator.Update();

            migrator = CreateMigrator <ShopContext_v1b>(contextKey: "NewOne");

            var scaffoldedMigration = migrator.ScaffoldInitialCreate("Foo");

            Assert.NotNull(scaffoldedMigration);
            Assert.NotSame(initialCreate, scaffoldedMigration);
            Assert.Equal(initialCreate.MigrationId, scaffoldedMigration.MigrationId);

            WhenNotSqlCe(
                () =>
                Assert.Contains("INSERT [dbo].[MigrationsCustomers]([CustomerNumber],", initialCreate.UserCode));
        }