コード例 #1
0
        static void Main(string[] args)
        {
            var dbMigrator = new DbMigrator(new Logger());

            var logger = new Logger();
            var installer = new Installer(logger);

            dbMigrator.Migrate();

            installer.Install();
        }
コード例 #2
0
        public void ExecuteSql_dispatches_to_interceptors()
        {
            var mockCommand = new Mock<DbCommand>();
            mockCommand.Setup(m => m.ExecuteNonQuery()).Returns(2013);

            var mockConnection = new Mock<DbConnection>();
            mockConnection.Protected().Setup<DbCommand>("CreateDbCommand").Returns(mockCommand.Object);

            var mockTransaction = new Mock<DbTransaction>(MockBehavior.Strict);
            mockTransaction.Protected().Setup<DbConnection>("DbConnection").Returns(mockConnection.Object);

            var migrator = new DbMigrator();
            var statement = new MigrationStatement
            {
                Sql = "Some Sql"
            };

            var providerFactoryServiceMock = new Mock<IDbProviderFactoryResolver>();
            providerFactoryServiceMock.Setup(m => m.ResolveProviderFactory(It.IsAny<DbConnection>()))
                .Returns(FakeSqlProviderFactory.Instance);
            MutableResolver.AddResolver<IDbProviderFactoryResolver>(k => providerFactoryServiceMock.Object);
            var mockInterceptor = new Mock<DbCommandInterceptor> { CallBase = true };
            DbInterception.Add(mockInterceptor.Object);
            var transactionInterceptorMock = new Mock<IDbTransactionInterceptor>();
            DbInterception.Add(transactionInterceptorMock.Object);
            try
            {
                new MigratorLoggingDecorator(migrator, new Mock<MigrationsLogger>().Object)
                    .ExecuteSql(mockTransaction.Object, statement, new DbInterceptionContext());
            }
            finally
            {
                MutableResolver.ClearResolvers();
                DbInterception.Remove(mockInterceptor.Object);
                DbInterception.Remove(transactionInterceptorMock.Object);
            }

            mockInterceptor.Verify(m => m.NonQueryExecuting(mockCommand.Object, It.IsAny<DbCommandInterceptionContext<int>>()), Times.Once());
            mockInterceptor.Verify(m => m.NonQueryExecuted(mockCommand.Object, It.IsAny<DbCommandInterceptionContext<int>>()), Times.Once());

            transactionInterceptorMock.Verify(
                m => m.ConnectionGetting(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext<DbConnection>>()),
                Times.Exactly(2));
            transactionInterceptorMock.Verify(
                m => m.ConnectionGot(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext<DbConnection>>()),
                Times.Exactly(2));
            mockTransaction.Protected().Verify<DbConnection>("DbConnection", Times.Exactly(2));
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: jimxshaw/samples-csharp
        /// <summary>
        /// Inheritance (is-A relationship)and composition (has-A relationship) allows for code reuse.
        /// Problems with inheritance: easy abuse by amateur devs, large hierarchies, fragility and tight code coupling.
        /// Any inheritance relationship can be translated to composition, which has code flexibility and is loosely coupled.
        /// </summary>
        static void Main(string[] args)
        {
            // Inheritance in action
            var text = new Text();
            text.Width = 200;
            text.Height = 500;
            text.Copy();


            // Composition in acton
            var dbMigrator = new DbMigrator(new Logger());

            var logger = new Logger();
            var installer = new Installer(logger);

            dbMigrator.Migrate();
            installer.Install();

            Console.ReadLine();
        }
コード例 #4
0
ファイル: AMSDbContext.cs プロジェクト: kgreed/AzureMyobSync
        public int RunMigrations()
        {
            var configuration = new DbMigrationsConfiguration();
            var migrator      = new DbMigrator(configuration);
            var pendings      = migrator.GetPendingMigrations().ToArray();

            Debug.Print($"There are {pendings.Count()} migrations");
            foreach (var pending in pendings)
            {
                Debug.Print(pending);
                try
                {
                    migrator.Update(pending);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            return(pendings.Length);
        }
コード例 #5
0
        private static void Main()
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists <BookstoreContext>());
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <BookstoreContext,
                                                                        Data.Migrations.Configuration>());

            var config   = new Data.Migrations.Configuration();
            var migrator = new DbMigrator(config);

            migrator.Update();

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            //ImportSimpleBooks();

            //ImportComplexBooks();

            //SimpleQuery("../../xml/test6.xml");

            ////SimpleQuery("../../reviews-queries.xml");

            SearchReviews();
        }
コード例 #6
0
        public override void InitializeDatabase(A0DbModel db)
        {
            var cs = (string)((dynamic)db.Database.Connection).ConnectionString;

            try
            {
                Trace.WriteLine($"DbMigrater.InitDb() - {cs}");
                var migrator = new DbMigrator(new DbMigrationsConfiguration());
                migrator.Update();

                var now = DateTime.Now;

                db.PcLogics.Load();
                foreach (var ur in db.PcLogics.Local)
                {
                    ur.Info = now.ToString();
                }
                ;

                Task.Run(async() => await db.TrySaveReportAsync());
            }
            catch (Exception ex) { ex.Log(cs); }
        }
コード例 #7
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);



            //Migration db
            Configuration configuration = new Configuration();

            configuration.ContextType = typeof(AuthenticationDB);
            var migrator = new DbMigrator(configuration);

            //This will get the SQL script which will update the DB and write it to debug
            //var scriptor = new MigratorScriptingDecorator(migrator);
            //string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null).ToString();
            //Debug.Write(script);

            //This will run the migration update script and will run Seed() method
            migrator.Update();
        }
        void IDatabaseInitializer <TContext> .InitializeDatabase(TContext context)
        {
            var doseed = !context.Database.Exists();
            // && new DatabaseTableChecker().AnyModelTableExists(context);
            // check to see if to seed - we 'lack' the 'AnyModelTableExists'
            // ...could be copied/done otherwise if needed...

            var migrator = new DbMigrator(_configuration);

            // if (doseed || !context.Database.CompatibleWithModel(false))
            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }

            // move on with the 'CreateDatabaseIfNotExists' for the 'Seed'
            base.InitializeDatabase(context);
            if (doseed)
            {
                Seed(context);
                context.SaveChanges();
            }
        }
コード例 #9
0
        public void InitializeDatabase(DbContext context)
        {
            bool flag = !context.Database.Exists() || !context.Database.CompatibleWithModel(false);

            if (flag)
            {
                DbMigrationsConfiguration configuration = new DbMigrationsConfiguration();
                DbMigrator dbMigrator = new DbMigrator(configuration);
                dbMigrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
                IEnumerable <string> pendingMigrations = dbMigrator.GetPendingMigrations();
                bool flag2 = pendingMigrations.Any <string>();
                if (flag2)
                {
                    MigratorScriptingDecorator migratorScriptingDecorator = new MigratorScriptingDecorator(dbMigrator);
                    string text  = migratorScriptingDecorator.ScriptUpdate(null, pendingMigrations.Last <string>());
                    bool   flag3 = !string.IsNullOrEmpty(text);
                    if (flag3)
                    {
                        context.Database.ExecuteSqlCommand(text, new object[0]);
                    }
                }
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: gunnisen/TcAndOctopusTest
        static void Main(string[] args)
        {
            var configuration = new Configuration();

            configuration.ContextType = typeof(MyDbContext);
            var migrator = new DbMigrator(configuration);

            migrator.Update();

            using (var db = new MyDbContext())
            {
                var albums = db.Albums.Include("Artist");
                foreach (var album in albums)
                {
                    Console.WriteLine($"{album.Artist.Name} - {album.Title}");
                }
            }
            if (Debugger.IsAttached)
            {
                Console.WriteLine("(Press <ENTER> to quit.)");
                Console.ReadLine();
            }
        }
コード例 #11
0
        public async Task MigrateAsync_SkipMigration_Ok()
        {
            var initialDbVersion = new DbVersion(1, 0);

            var provider = new Mock <IDbProvider>();

            provider
            .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(new [] { initialDbVersion } as IReadOnlyCollection <DbVersion>));

            provider
            .Setup(x => x.BeginTransaction())
            .Returns(() => new MockTransaction());

            var migrations = new List <IMigration>(0);

            var migrator = new DbMigrator(
                provider.Object,
                migrations,
                MigrationPolicy.Allowed,
                MigrationPolicy.Forbidden,
                null,
                initialDbVersion);

            var result = await migrator.MigrateSafeAsync();

            provider
            .Verify(x => x.SaveAppliedMigrationVersionAsync(It.IsAny <string>(), It.IsAny <DbVersion>(), It.IsAny <CancellationToken>()), Times.Never);

            provider
            .Verify(x => x.CreateDatabaseIfNotExistsAsync(It.IsAny <CancellationToken>()), Times.Never);

            provider
            .Verify(x => x.CreateAppliedMigrationsTableIfNotExistsAsync(It.IsAny <CancellationToken>()), Times.Never);

            Assert.True(result.IsSuccessfully);
        }
コード例 #12
0
        public static void ConfigureMobileApp(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686
            config.EnableSystemDiagnosticsTracing();

            new MobileAppConfiguration()
            .UseDefaultConfiguration()
            .ApplyTo(config);

            // Use Entity Framework Code First to create database tables based on your DbContext
            //Database.SetInitializer(new XamarinHandsOnLabInitializer());

            var migrator = new DbMigrator(new Migrations.Configuration());

            migrator.Update();

            // To prevent Entity Framework from modifying your database schema, use a null database initializer
            // Database.SetInitializer<XamarinHandsOnLabContext>(null);

            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            if (string.IsNullOrEmpty(settings.HostName))
            {
                // This middleware is intended to be used locally for debugging. By default, HostName will
                // only have a value when running in an App Service application.
                app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
                {
                    SigningKey     = ConfigurationManager.AppSettings["SigningKey"],
                    ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                    ValidIssuers   = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                    TokenHandler   = config.GetAppServiceTokenHandler()
                });
            }
            app.UseWebApi(config);
        }
コード例 #13
0
        public static void Main(string[] args)
        {
            // read the metadata from the table
            // foreach row in the metadata table
            // Create a class  using dynamic class.


            List <IDynamicClassFields> dynamicClassFields = new List <IDynamicClassFields>()
            {
                new DynamicClassFields()
                {
                    FieldName = "Id", FieldType = typeof(Int32)
                },
                new DynamicClassFields()
                {
                    FieldName = "Name", FieldType = typeof(string)
                }
            };


            var DemoClass = MyTypeBuilder.CreateNewObject(dynamicClassFields, "Demo");

            object value = "sharuk";

            MyTypeBuilder.SetValue(DemoClass, "Name", value);

            CodeFirstDynamicModelEF codeFirstDynamicModelEF = new CodeFirstDynamicModelEF();
            var configuration = new Configuration();
            var migrator      = new DbMigrator(configuration);

            migrator.Update();
            codeFirstDynamicModelEF.MyEntities.Add(new MyEntity());
            codeFirstDynamicModelEF.Set(DemoClass.GetType()).Add(DemoClass);


            codeFirstDynamicModelEF.SaveChanges();
        }
コード例 #14
0
        /// <summary>
        /// Ищет конкретную миграцию в БД по имени миграции
        /// </summary>
        /// <param name="migration">Название миграции</param>
        /// <returns>Результат проверки миграций</returns>
        public string CheckByMigrationName(string migration)
        {
            var migrator = new DbMigrator(_configuration);

            var targetMigration =
                migrator.GetLocalMigrations()
                .Where(s => s.ToLowerInvariant().Contains(migration.ToLowerInvariant()))
                .ToList();

            if (targetMigration.Count > 1)
            {
                throw new MigrationsException(string.Format(Constants.NotUniqMigration,
                                                            Environment.NewLine,
                                                            targetMigration.Join(separator: Environment.NewLine)));
            }

            if (targetMigration.Count == 0)
            {
                throw new MigrationsException(string.Format(Constants.MigrationNotFound, migration));
            }

            var targetMigrationDb = migrator.GetDatabaseMigrations(migration, false).ToList();

            if (targetMigrationDb.Count > 1)
            {
                throw new MigrationsException(string.Format(Constants.NotUniqMigration,
                                                            Environment.NewLine,
                                                            targetMigrationDb.Join(separator: Environment.NewLine)));
            }

            if (targetMigrationDb.Count == 0)
            {
                throw new MigrationsException(string.Format(Constants.MigrationNotFound, migration));
            }

            return(migrator.CheckMigrations(targetMigration.First(), targetMigrationDb.First(), false));
        }
コード例 #15
0
        public async Task MigrateAsync_HaveHalf_AllIsMigrated()
        {
            var resolver = new EmbeddedResourceMigrationResolver(typeof(MigrationFixtures.R));

            // Part 1
            var migration = new DbMigrator(new ListMigrationResolver(resolver.Resolve().Take(2).ToList()));
            await migration.MigrateAsync(Database.ConnectionString);

            await using var cnn = await Database.ConnectionFactory.OpenAsync();

            var fruits = await cnn.QueryAsync <string>("SELECT [Name] FROM [Fruit] ORDER BY [Created] ASC");

            Assert.That(fruits, Is.EqualTo(new [] { "Banana" }));

            // Part 2
            migration = new DbMigrator(resolver);
            await migration.MigrateAsync(Database.ConnectionString);

            await using var cnn2 = await Database.ConnectionFactory.OpenAsync();

            fruits = await cnn.QueryAsync <string>("SELECT [Name] FROM [Fruit] ORDER BY [Created] ASC");

            Assert.That(fruits, Is.EqualTo(new[] { "Banana", "Apple", "Orange" }));
        }
コード例 #16
0
ファイル: NoteService.cs プロジェクト: one3chens/Knowte
        private async Task InitializeStorageIfRequiredAsync(string newLocation)
        {
            await Task.Run(() =>
            {
                // Database file
                var migrator = new DbMigrator(newLocation);

                if (migrator.DatabaseExists())
                {
                    migrator.UpgradeDatabase();
                }
                else
                {
                    migrator.InitializeNewDatabase();
                }

                // Notes directory
                string notesDirectoryPath = newLocation;
                if (!Directory.Exists(notesDirectoryPath))
                {
                    Directory.CreateDirectory(notesDirectoryPath);
                }
            });
        }
コード例 #17
0
        /// <summary>
        /// Открыть БД с выполнением автоматической миграции
        /// </summary>
        /// <returns></returns>
        public static DB Open()
        {
            // Инициализатор с поддержкой миграции БД
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <DB, Migrations.Configuration>());

            var  db         = new DB();
            bool doMiration = false;

            try
            {
                doMiration = !db.Database.CompatibleWithModel(true);
            }
            catch (Exception)
            {
                doMiration = true;
            }
            if (doMiration)
            {
                var cfg = new Migrations.Configuration();
                var mgr = new DbMigrator(cfg);
                mgr.Update();
            }
            return(db);
        }
コード例 #18
0
ファイル: DbUpdateCommand.cs プロジェクト: mrpastewart/Core
        public string Execute(DbUpdateArgs args)
        {
            _console.WriteLine("Starting the Resgrid Database Update Process");
            WriteConnectionString();

            _console.WriteLine("Please Wait...");

            try
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion <Repositories.DataRepository.Contexts.DataContext, Repositories.DataRepository.Migrations.Configuration>());
                var migrator = new DbMigrator(new Repositories.DataRepository.Migrations.Configuration());
                migrator.Update();

                _console.WriteLine("Completed updating the Resgrid Database!");
            }
            catch (Exception ex)
            {
                _console.WriteLine("There was an error trying to update the Resgrid Database, see the error output below:");
                _console.WriteLine(ex.ToString());
            }


            return("");
        }
コード例 #19
0
        public void MigrateDatabase()
        {
            //Arrange

            Animals.Migrations.Configuration config = new Configuration();
            DbMigrator migrator = new DbMigrator(config);

            Console.WriteLine("Past migrations:");
            foreach (string s in migrator.GetDatabaseMigrations())
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("Local migrations:");
            foreach (string s in migrator.GetLocalMigrations())
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("Pending migrations:");
            foreach (string s in migrator.GetPendingMigrations())
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("Migrating...");
            foreach (string s in migrator.GetPendingMigrations())
            {
                //Act
                Console.WriteLine("Applying migration {0}", s);
                Action act = () => migrator.Update(s);

                //Assert
                act.ShouldNotThrow();
            }
        }
コード例 #20
0
        protected void Application_Start()
        {
            var updateSchemaApp = new DbMigrator(new Migrations.Configuration());

            updateSchemaApp.Update();


            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            JsonMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.OfType <JsonMediaTypeFormatter>().FirstOrDefault();

            formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
            GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
        }
コード例 #21
0
ファイル: Global.asax.cs プロジェクト: AntieJ/RecipeScrapbook
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //http://blogs.msdn.com/b/webdev/archive/2014/04/09/ef-code-first-migrations-deployment-to-an-azure-cloud-service.aspx
            if (bool.Parse(ConfigurationManager.AppSettings["MigrateDatabaseToLatestVersion"]))
            {
                var configuration = new RecipePrototype.Migrations.Configuration();
                var migrator      = new DbMigrator(configuration);
                migrator.Update();
            }

            //http://docs.autofac.org/en/latest/integration/mvc.html
            var builder = new ContainerBuilder();

            builder.RegisterType <HomeController>().InstancePerRequest();
            builder.RegisterModule <AutofacRegistration>();
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
コード例 #22
0
        /// <summary>
        /// Run Automatic migrations
        /// </summary>
        public void UpdateAutoMigrations(string connectionName, DbMigrationsConfiguration migrationConfig)   // < DataContext >
        //
        {
            if (_ty.TypeInitializer != null)
            {
                var _tempType = Activator.CreateInstance <T>();
                //_ty.TypeInitializer.Invoke(null, null);
            }
            DbMigrationsConfiguration config = migrationConfig ?? new DbMigrationsConfiguration //<DataContext>
            {
                AutomaticMigrationsEnabled        = true,
                AutomaticMigrationDataLossAllowed = false,
            };

            Trace.WriteLine("Migrating " + _ty.Name + " with migrator config: " + config.GetType().ToString());
            config.MigrationsAssembly  = _ty.Assembly;
            config.MigrationsNamespace = _ty.Namespace;
            config.ContextKey          = _ty.Name;
            config.ContextType         = this.GetType();
            config.TargetDatabase      = new DbConnectionInfo(connectionName);
            var migrator = new DbMigrator(config);

            migrator.Update();
        }
コード例 #23
0
        private static void UpdateDatabase(IConnectionSettings connectionSettings)
        {
            switch (connectionSettings.ProviderInvariantName)
            {
            case DataConfiguration.SqlServerProviderInvariantName:
                FixDatabase(connectionSettings, new Migrations.SqlServer.V1());
                break;

            case DataConfiguration.SqlServerCompactProviderInvariantName:
                FixDatabase(connectionSettings, new Migrations.SqlCE.V1());
                break;

            case DataConfiguration.OracleDBProviderInvariantName:
            {
                var userId = ConnectionStringParser.TryGetValue(connectionSettings.ConnectionString, "USER ID");

                if (null == userId)
                {
                    throw new InvalidOperationException("null == userId");
                }

                Migrations.OracleDB.V2.Schema = userId.ToUpper();
            }
            break;
            }

            DataContext.ConnectionSettings = connectionSettings;

            var configuration = new Configuration();

            configuration.SetDirectoryAndNamespace(connectionSettings.ProviderInvariantName);

            var migrator = new DbMigrator(configuration);

            migrator.Update();
        }
コード例 #24
0
        static JerryPlatDbContext()
        {
            using (JerryPlatDbContext context = new JerryPlatDbContext())
            {
                if (context.Database.Exists())
                {
                    Database.SetInitializer <JerryPlatDbContext>(null);
                    var migrator = new DbMigrator(new Configuration());
                    // if (doseed || !context.Database.CompatibleWithModel(false))
                    if (migrator.GetPendingMigrations().Any())
                    {
                        migrator.Update();
                    }
                }
                else
                {
                    Database.SetInitializer(new CreateAndMigrateDatabaseInitializer <Configuration>());
                }

                context.Database.Initialize(false);

                SystemConfigModel.Reset(context.SystemConfigs.ToDictionary(o => o.Name, o => o.Config));
            }
        }
コード例 #25
0
        public static bool CreateDatabase(string dbName, string dbFileName)
        {
            try
            {
                string connectionString = String.Format(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True");
                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand cmd = connection.CreateCommand();


                    DetachDatabase(dbName);

                    cmd.CommandText = String.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", dbName, dbFileName);
                    cmd.ExecuteNonQuery();

                    // Execute Seed
                    var configuration = new Configuration();
                    var migrator      = new DbMigrator(configuration);
                    migrator.Update();
                }

                if (File.Exists(dbFileName))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                throw;
            }
        }
コード例 #26
0
        public void InitializeDatabase(TContext context) // Update the migrator with the config containing the right connection string
        {
            var dbMigrator = new DbMigrator(configuration);

            dbMigrator.Update();
        }
コード例 #27
0
        private void UpdateDatabase()
        {
            var migrator = new DbMigrator(new DataAccess.Migrations.Configuration());

            migrator.Update();
        }
コード例 #28
0
 private MigratorBase DecorateMigrator(DbMigrator migrator)
 {
     return new MigratorLoggingDecorator(migrator, Log);
 }
コード例 #29
0
        public static void Initialize(string connectionString)
        {
            var bld = new SqlConnectionStringBuilder(connectionString);
            //get name of database to connect
            var dbName = bld.InitialCatalog;

            //get connection string to Master database
            bld.InitialCatalog = "master";
            var masterConnectionString = bld.ConnectionString;

            //create the database, if it doesn't exist
            bool shouldRunSeed = false;

            using (var cnn = new SqlConnection(masterConnectionString))
            {
                var cmdString1 =
                    string.Format("select * from sys.databases where name='{0}'",
                                  dbName);
                var cmdString2 =
                    string.Format("create database {0}",
                                  dbName);
                int result;
                using (var cmd = new System.Data.SqlClient.SqlCommand(cmdString1, cnn))
                {
                    cmd.Connection.Open();
                    result = cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    if (result == 0)
                    {
                        using (var cmd2 = new SqlCommand(cmdString2, cnn))
                        {
                            cmd2.Connection.Open();
                            cmd2.ExecuteNonQuery();
                        }
                        shouldRunSeed = true;
                    }
                }
            }

            var connectionInfo = new System.Data.Entity.Infrastructure.DbConnectionInfo(connectionString, "System.Data.SqlClient");

            var config = new DbMigrationsConfiguration();

            config.TargetDatabase = connectionInfo;

            var migrator = new DbMigrator(config);

            migrator.Configuration.AutomaticMigrationDataLossAllowed = true;
            migrator.Configuration.AutomaticMigrationsEnabled        = true;
            var pendingMigrations = migrator.GetPendingMigrations();


            if (pendingMigrations.Any())
            {
                System.Threading.Thread.Sleep(5000);
                migrator.Update();
                if (shouldRunSeed)
                {
                    var ctx2 = new DataContext();
                    Seed(ctx2);
                }
            }
            migrator.Configuration.AutomaticMigrationsEnabled = false;
        }
コード例 #30
0
ファイル: Migrate.cs プロジェクト: rvriens/ExampleEF
        public void DoMigration()
        {
            //using (var db = new WebLibrary.BloggingContext(_connectionString))
            //{



            //}

            //System.Data.Entity.MigrateDatabaseToLatestVersion<>

            //        var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(
            //            new WebLibrary.Migrations.InitialCreate
            //new Lcmp.EF.Migrations.Migrations.Configuration());
            //        dbMigrator.Update();
            //    }



            DbMigrationsConfiguration configuration = BloggingContext.CreateConfiguration();  //new WebLibrary.Migrations.Configuration();

            var dbmigrator = new DbMigrator(configuration);

            dbmigrator.Configuration.TargetDatabase = new DbConnectionInfo(_connectionString, "System.Data.SqlClient");
            //new DbConnectionInfo("Data Source=.;Initial Catalog=Blogging;User ID=blogging;Password=blogging", "System.Data.SqlClient");
            foreach (string migration in dbmigrator.GetPendingMigrations())
            {
                Console.WriteLine(string.Format("{0}", migration));
            }

            // Database.SetInitializer(new MigrateDatabaseToLatestVersion<WebLibrary.BloggingContext, WebLibrary.Migrations.Configuration>());

            Database.SetInitializer <WebLibrary.BloggingContext>(null);
            var migrations = dbmigrator.GetPendingMigrations();

            if (migrations.Any())
            {
                var scriptor = new MigratorScriptingDecorator(dbmigrator);
                using (var db = new WebLibrary.BloggingContext(_connectionString))
                {
                    using (var dbContextTransaction = db.Database.BeginTransaction())
                    {
                        string prevMigration = null;
                        foreach (string migration in dbmigrator.GetPendingMigrations())
                        {
                            string script = scriptor.ScriptUpdate(prevMigration, migration);
                            if (!String.IsNullOrEmpty(script))
                            {
                                Console.WriteLine(string.Format("{0}: {1}", migration, script));


                                db.Database.Initialize(false);
                                db.Database.ExecuteSqlCommand(script);
                            }
                            prevMigration = migration;
                        }
                        dbContextTransaction.Commit();
                    }
                }
            }
            //dbmigrator.Update();
        }
コード例 #31
0
 private MigratorBase DecorateMigrator(DbMigrator migrator)
 {
     return((MigratorBase) new MigratorLoggingDecorator((MigratorBase)migrator, (MigrationsLogger)this.Log));
 }
コード例 #32
0
        public static void MigrateDatabase()
        {
            var dbMigrator = new DbMigrator(new Configuration());

            dbMigrator.Update();
        }
コード例 #33
0
        public OperationResult UpdateConnectionString(InitialSettingsModel initialSettingsModel)
        {
            if (!ModelState.IsValid)
            {
                return(new OperationResult(false, "Required fields are not filled"));
            }

            var        inputPath = System.Web.Hosting.HostingEnvironment.MapPath("~/bin/Input.txt");
            AdminTools adminTools;
            var        sdkConnectionString = "Data Source="
                                             + initialSettingsModel.ConnectionStringSdk.Source + ";Initial Catalog="
                                             + initialSettingsModel.ConnectionStringSdk.Catalogue + ";"
                                             + initialSettingsModel.ConnectionStringSdk.Auth;

            var mainConnectionString = "Data Source="
                                       + initialSettingsModel.ConnectionStringMain.Source + ";Initial Catalog="
                                       + initialSettingsModel.ConnectionStringMain.Catalogue + ";"
                                       + initialSettingsModel.ConnectionStringMain.Auth;

            try
            {
                if (File.Exists(inputPath))
                {
                    //File.Delete(inputPath);
                    //var fileStream = File.Create(inputPath);
                    //fileStream.Dispose();
                    return(new OperationResult(false, "Connection string already exist"));
                }

                var fileStream = File.Create(inputPath);
                fileStream.Dispose();

                File.WriteAllText(inputPath, sdkConnectionString);
            }
            catch (Exception exception)
            {
                Logger.Error(exception.Message);
                return(new OperationResult(false, "Could not write connection string in /bin/Input.txt"));
            }
            try
            {
                adminTools = new AdminTools(sdkConnectionString);
            }
            catch (Exception exception)
            {
                Logger.Error(exception.Message);
                return(new OperationResult(false, "SDK connection string is invalid"));
            }

            var configuration = WebConfigurationManager.OpenWebConfiguration("~");
            var section       = (ConnectionStringsSection)configuration.GetSection("connectionStrings");

            section.ConnectionStrings["eFormMainConnection"].ConnectionString = mainConnectionString;
            try
            {
                configuration.Save();
                ConfigurationManager.RefreshSection("connectionStrings");
                var migrationConfiguration = new EformMigrationsConfiguration(mainConnectionString)
                {
                    TargetDatabase = new DbConnectionInfo(mainConnectionString, "System.Data.SqlClient")
                };
                var migrator = new DbMigrator(migrationConfiguration);
                migrator.Update();
                var settingsHelper = new SettingsHelper(mainConnectionString);
                settingsHelper.CreateAdminUser(initialSettingsModel.AdminSetupModel);
            }
            catch (Exception exception)
            {
                Logger.Error(exception.Message);
                return(new OperationResult(false, "Main connection string is invalid"));
            }

            adminTools.DbSetup(initialSettingsModel.ConnectionStringSdk.Token);
            return(new OperationResult(true));
        }
コード例 #34
0
 static void Main(string[] args)
 {
     var dbMigrator = new DbMigrator(new FileLogger("C:\\Projects\\log.txt"));
     dbMigrator.Migrate();
 }
コード例 #35
0
        /// <summary>
        ///     Initializes a new instance of the MigrationScaffolder class.
        /// </summary>
        /// <param name = "migrationsConfiguration">Configuration to be used for scaffolding.</param>
        public MigrationScaffolder(DbMigrationsConfiguration migrationsConfiguration)
        {
            Contract.Requires(migrationsConfiguration != null);

            _migrator = new DbMigrator(migrationsConfiguration);
        }
コード例 #36
0
 private MigratorBase DecorateMigrator(DbMigrator migrator)
 {
     return(new MigratorLoggingDecorator(migrator, Log));
 }
コード例 #37
0
        /// <summary>
        /// Initializes a new instance of the MigrationScaffolder class.
        /// </summary>
        /// <param name="migrationsConfiguration"> Configuration to be used for scaffolding. </param>
        public MigrationScaffolder(DbMigrationsConfiguration migrationsConfiguration)
        {
            Check.NotNull(migrationsConfiguration, "migrationsConfiguration");

            _migrator = new DbMigrator(migrationsConfiguration);
        }