Beispiel #1
0
        public void InitializeDatabase(ScheduleMasterContext context)
        {
            if (context.Database.Exists())
            {
                bool comaptible;

                try
                {
                    comaptible = context.Database.CompatibleWithModel(true);
                }
                catch
                {
                    comaptible = false;
                }

                if (!comaptible)
                {
                    var migration = new MigrateDatabaseToLatestVersion <ScheduleMasterContext, Configuration>();

                    migration.InitializeDatabase(context);
                }
            }
            else
            {
                context.Database.Create();
            }
        }
Beispiel #2
0
        protected virtual void CreateOrMigrate(TenantBase tenant)
        {
            var args = new DbPerTenantConnectionStringResolveArgs(
                tenant == null ? (int?)null : (int?)tenant.Id,
                tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant
                );

            args["DbContextType"]         = typeof(TDbContext);
            args["DbContextConcreteType"] = typeof(TDbContext);

            var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(_connectionStringResolver.GetNameOrConnectionString(args));

            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                using (var dbContext = _iocResolver.ResolveAsDisposable <TDbContext>(new { nameOrConnectionString = nameOrConnectionString }))
                {
                    var dbInitializer = new MigrateDatabaseToLatestVersion <TDbContext, TConfiguration>(
                        true,
                        new TConfiguration
                    {
                        Tenant = tenant
                    });

                    dbInitializer.InitializeDatabase(dbContext.Object);

                    _unitOfWorkManager.Current.SaveChanges();
                    uow.Complete();
                }
            }
        }
        /// <summary>
        /// 获取context
        /// </summary>
        /// <returns></returns>
        internal BusinessDBContext GetDBContext()
        {
            try
            {
                //mysql连接字符串
                //var connectionString = $"Data Source={AppConfig.DB_DataSource};Port={AppConfig.DB_Port};Initial Catalog={CommonHelper.Instance.GetCurrentDBName()};User ID={AppConfig.DB_UserID};Password={AppConfig.DB_Password};";

                //sqlserver连接字符串
                var connectionString = $"Data Source={AppConfig.DB_DataSource},{AppConfig.DB_Port};Initial Catalog={CommonHelper.Instance.GetCurrentDBName()};User ID={AppConfig.DB_UserID};Password={AppConfig.DB_Password};";

                var context = new BusinessDBContext(connectionString);

                //数据库是否存在 不存在则创建
                if (!context.Database.Exists())
                {
                    context.Database.Create();

                    var dbInitializer = new MigrateDatabaseToLatestVersion <BusinessDBContext, Migrations.Configuration>(true);
                    dbInitializer.InitializeDatabase(context);
                }

                //数据库接口是否和模型一致 不一致则更新
                if (!context.Database.CompatibleWithModel(false))
                {
                    var dbInitializer = new MigrateDatabaseToLatestVersion <BusinessDBContext, Migrations.Configuration>(true);
                    dbInitializer.InitializeDatabase(context);
                }

                return(context);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #4
0
        private static void UpdateDatabase()
        {
            var migrator = new MigrateDatabaseToLatestVersion <NetworkContext, Data.Migrations.Configuration>();

            migrator.InitializeDatabase(new NetworkContext());
            Console.WriteLine("Database is updated.");
        }
Beispiel #5
0
        public static void Initialize()
        {
            var initializeMigrations =
                new MigrateDatabaseToLatestVersion <MyDataContext, Migrations.Configuration>();

            initializeMigrations.InitializeDatabase(new MyDataContext());
        }
        /// <summary>
        /// 获取context
        /// </summary>
        /// <returns></returns>
        internal MasterDBContext GetDBContext()
        {
            try
            {
                var context = new MasterDBContext();

                if (!context.Database.Exists())
                {
                    context.Database.Create();

                    var dbInitializer = new MigrateDatabaseToLatestVersion <MasterDBContext, Migrations.Configuration>(true);
                    dbInitializer.InitializeDatabase(context);
                }

                if (!context.Database.CompatibleWithModel(false))
                {
                    var dbInitializer = new MigrateDatabaseToLatestVersion <MasterDBContext, Migrations.Configuration>(true);
                    dbInitializer.InitializeDatabase(context);
                }

                return(context);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #7
0
        public void MigrateDatabaseToLatestVersion_throws_when_given_invalid_connection_name()
        {
            var init = new MigrateDatabaseToLatestVersion <EmptyContext, TestMigrationsConfiguration>("YouWontFindMe");

            Assert.Equal(
                Strings.DbContext_ConnectionStringNotFound("YouWontFindMe"),
                Assert.Throws <InvalidOperationException>(() => init.InitializeDatabase(new EmptyContext())).Message);
        }
Beispiel #8
0
 private void initDatabase()
 {
     using (DatabaseContext database = new DatabaseContext())
     {
         MigrateDatabaseToLatestVersion <DatabaseContext, Configuration> migrate = new MigrateDatabaseToLatestVersion <DatabaseContext, Configuration>();
         Database.SetInitializer <DatabaseContext>(migrate);
         migrate.InitializeDatabase(database);
     }
 }
        private static void CreateDatabase()
        {
            ExecuteSQLCommand(
                MasterDBConnectionStr,
                $"CREATE DATABASE [{DBNAME}] ON (NAME='{DBNAME}', FILENAME='{FileName}')");

            var migration = new MigrateDatabaseToLatestVersion <CompanyDBContext, CompanyDBConfiguration>();

            migration.InitializeDatabase(new CompanyDBContext());
        }
Beispiel #10
0
        public void InitializeDatabase(TContext context)
        {
            var step1 = new DropCreateDatabaseAlways <TContext>();

            step1.InitializeDatabase(context);

            var step2 = new MigrateDatabaseToLatestVersion <TContext, TMigrationsConfiguration>();

            step2.InitializeDatabase(context);
        }
Beispiel #11
0
        public void Start()
        {
            // create context
            var context = new SqlLoggerContext(_configuration.Connection);

            // create database migrator
            var migrator = new MigrateDatabaseToLatestVersion <SqlLoggerContext, Configuration>();

            // update database to latest version
            migrator.InitializeDatabase(context);
        }
Beispiel #12
0
        public void MigrateDatabaseToLatestVersion_invokes_migrations_pipeline_to_latest_version()
        {
            var init = new MigrateDatabaseToLatestVersion <EmptyContext, TestMigrationsConfiguration>();

            TestMigrationsConfiguration.SeedCalled = false;

            init.InitializeDatabase(new EmptyContext());

            // If seed gets called we know the migrations pipeline was invoked to update to the latest version
            Assert.True(TestMigrationsConfiguration.SeedCalled);
        }
Beispiel #13
0
        public static void InitTestDatabase()
        {
            var testDatabase = new Migrations.TestDatabase();

            testDatabase.CreateOrRefreshDatabase(Seed: () =>
            {
                var migrate   = new MigrateDatabaseToLatestVersion <DatabaseContext, Migrations.ConfigurationDefault>();
                var dbContext = new DatabaseContext();
                migrate.InitializeDatabase(dbContext);
            });
            testDatabase.SetAppDomainDataDirectory();
        }
 public SimpleMembershipInitializer()
 {
     Database.SetInitializer<WomContext>(null);
     
     // forcing the application of the migrations so the users table is modified before
     // the code below tries to create it. 
     var migrations = new MigrateDatabaseToLatestVersion<WomContext, Wom.Migrations.Configuration>();
     var context = new WomContext(); 
     migrations.InitializeDatabase(context); 
     
     try
     {....
Beispiel #15
0
        private void CreateDatabase()
        {
            ExecuteSqlCommand(Master, $@"
                CREATE DATABASE [TestEmployeeDB]
                ON (NAME = 'TestEmployeeDB',
                FILENAME = '{Filename}')");

            var commonMigration = new MigrateDatabaseToLatestVersion <EmployeesDbContext
                                                                      , EmployeesMigrationConfiguration>("EmployeeConnectionString");

            commonMigration.InitializeDatabase(new EmployeesDbContext());
        }
Beispiel #16
0
        private void CreateDatabase()
        {
            ExecuteSqlCommand(Master, $@"
                CREATE DATABASE [SanabelSecurityTestDB]
                ON (NAME = 'SanabelSecurityTestDB',
                FILENAME = '{Filename}')");

            var migration = new MigrateDatabaseToLatestVersion <Security.DataAccessLayer.SecurityContext
                                                                , Security.DataAccessLayer.Migrations.SecurityMigrationsConfiguration>("SecurityConnectionString");

            migration.InitializeDatabase(new DataAccessLayer.SecurityContext());
        }
Beispiel #17
0
        /// <summary>
        /// Runs the migration
        /// </summary>
        /// <remarks>
        /// We can do this, or just run Update-Database in the IDE command line
        /// </remarks>
        /// <param name="args">Console arguments</param>
        static void Main(string[] args)
        {
            SetConnectionString(args);

            var databaseInitializer = new MigrateDatabaseToLatestVersion<EntityMigrateDatabaseContext, EntityMigrationConfiguration>();
            var databaseContext = new EntityMigrateDatabaseContext();

            databaseInitializer.InitializeDatabase(databaseContext);

            // Run any post migration work here (ex: installing SSIS packages, building matching database, etc)
            // --> databaseContext.Database.ExecuteSqlCommand()
        }
Beispiel #18
0
        protected override void Init()
        {
            Database.SetInitializer <BralekDbContext>(null);

            // forcing the application of the migrations so the users table is modified before
            // the code below tries to create it.
            using (var context = new BralekDbContext("DefaultConnection"))
            {
                var migrations = new MigrateDatabaseToLatestVersion <BralekDbContext, Configuration>();
                migrations.InitializeDatabase(context);
            }
        }
Beispiel #19
0
        public void MigrateDatabaseToLatestVersion_use_connection_name_from_config_file()
        {
            var init =
                new MigrateDatabaseToLatestVersion <EmptyContext, TestMigrationsConfiguration>(
                    "MigrateDatabaseToLatestVersionNamedConnectionTest");

            TestMigrationsConfiguration.SeedDatabase = null;

            init.InitializeDatabase(new EmptyContext());

            Assert.Equal("MigrationInitFromConfig", TestMigrationsConfiguration.SeedDatabase);
        }
 void IDatabaseInitializer <TContext> .InitializeDatabase(TContext context)
 {
     if (context.Database.Exists())
     {
         if (!context.Database.CompatibleWithModel(throwIfNoMetadata: false))
         {
             var migrationInitializer = new MigrateDatabaseToLatestVersion <TContext, TConfiguration>(true);
             migrationInitializer.InitializeDatabase(context);
         }
     }
     base.InitializeDatabase(context);
 }
        protected override void Init()
        {
            Database.SetInitializer<BralekDbContext>(null);

            // forcing the application of the migrations so the users table is modified before
            // the code below tries to create it.
            using (var context = new BralekDbContext("DefaultConnection"))
            {
                var migrations = new MigrateDatabaseToLatestVersion<BralekDbContext, Configuration>();
                migrations.InitializeDatabase(context);
            }
        }
Beispiel #22
0
        private void CreateDatabase()
        {
            ExecuteSqlCommand(Master, $@"
                CREATE DATABASE [CommonSettingSanabelTestDB]
                ON (NAME = 'CommonSettingSanabelTestDB',
                FILENAME = '{Filename}')");

            var migration = new MigrateDatabaseToLatestVersion <CommonSettings.DAL.CommonSettingDataContext
                                                                , CommonSettings.DAL.Migrations.CommonSettingsDbMigrationsConfiguration>("CommonSettingConnectionString");

            migration.InitializeDatabase(new CommonSettings.DAL.CommonSettingDataContext());
        }
Beispiel #23
0
        private static void CreateDatabase()
        {
            ExecuteSqlCommand(Master, $@"
                CREATE DATABASE [Globalmantics]
                ON (NAME = 'Globalmantics',
                FILENAME = '{Filename}')");

            var migration = new MigrateDatabaseToLatestVersion <
                GlobalmanticsContext, GlobalmanticsConfiguration>();

            migration.InitializeDatabase(new GlobalmanticsContext());
        }
Beispiel #24
0
        private static void CreateDatabase()
        {
            ExecuteSqlCommand(Master, string.Format(SqlResource.DatabaseScript, FileName));

            //Use T-Sql Scripts For Create Database
            //ExecuteSqlCommand(MyAppTest, SqlResources.V1_0_0);

            var migration =
                new MigrateDatabaseToLatestVersion <ApplicationDbContext, DataLayer.Migrations.Configuration>();

            migration.InitializeDatabase(new ApplicationDbContext());
        }
        public static void CreateDatabase()
        {
            // Create database
            ExecuteSqlCommand(Master, $@"
                CREATE DATABASE [Widgets]
                ON (NAME = 'Widgets',
                FILENAME = '{Filename}')");

            // Run the database migration
            var migration = new MigrateDatabaseToLatestVersion <WidgetsContext, WidgetsConfiguration>();

            migration.InitializeDatabase(new WidgetsContext());
        }
        private static void CreateDatabase()
        {
            testDatabaseConnection = string.Format(connectionString, Guid.NewGuid().ToString("N"));

            using (var db = new Core.Database.DbContext(testDatabaseConnection))
            {
                db.Database.CreateIfNotExists();

                var migration = new MigrateDatabaseToLatestVersion <Core.Database.DbContext, KPMGDbMigrationConfiguration>(true);

                migration.InitializeDatabase(db);
            }
        }
        public static void AssemblyInit(TestContext context)
        {
            const string connectionStringName = "ProductContext";

            CreateTestDatabase.TestDatabase.Create(connectionStringName);

            //optional - run Entity Framework migrations
            var migrate = new MigrateDatabaseToLatestVersion<ProductContext, Configuration>(connectionStringName);
            using (var dbContext = new ProductContext())
            {
                migrate.InitializeDatabase(dbContext);
            }
        }
Beispiel #28
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Init database
            var DbInitilizer = new MigrateDatabaseToLatestVersion <DementorDatabase, Configuration>();

            DbInitilizer.InitializeDatabase(new DementorDatabase());
        }
Beispiel #29
0
        public static void AssemblyInit(TestContext context)
        {
            const string connectionStringName = "ProductContext";

            CreateTestDatabase.TestDatabase.Create(connectionStringName);

            //optional - run Entity Framework migrations
            var migrate = new MigrateDatabaseToLatestVersion <ProductContext, Configuration>(connectionStringName);

            using (var dbContext = new ProductContext())
            {
                migrate.InitializeDatabase(dbContext);
            }
        }
Beispiel #30
0
 private void btnUpdate_Click(object sender, EventArgs e)
 {
     using (var db = new EFCodeFirstContext())
     {
         if (!db.Database.CompatibleWithModel(true))
         {
             var initializer = new MigrateDatabaseToLatestVersion <EFCodeFirstContext, EFCodeFirst.Data.Migrations.Configuration>();
             initializer.InitializeDatabase(db);
             lblMessage.Text   = "Veritabanı güncellendi.";
             btnUpdate.Enabled = false;
             btnScript.Enabled = false;
         }
     }
 }
        public void InitializeDatabase(TContext context)
        {
            if (context.Database.Exists())
            {
                // set the database to SINGLE_USER so it can be dropped
                context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

                // drop the database
                context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
            }

            var migrator = new MigrateDatabaseToLatestVersion <TContext, TMigrationsConfiguration>();

            migrator.InitializeDatabase(context);
        }
Beispiel #32
0
        public static void ClassSetup(TestContext context)
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Empty));

            //use this database file name (in current bin folder)
            var testDatabase = new TestDatabase("UnitTestDB");

            testDatabase.CreateDatabase();

            //if we're using Entity Framework Code First, run all the migrations.
            var migrate   = new MigrateDatabaseToLatestVersion <TestDBContext, Configuration>();
            var dbContext = new TestDBContext();

            migrate.InitializeDatabase(dbContext);
        }
        protected void Application_Start()
        {
            ApplicationDBContext db = new ApplicationDBContext();

            //Init the datbase, and apply any pending updates/changes
            //NOTE: Entity Framework MUST update the database BEFORE the following WebSecurity block.
            //  If Entity Framework does not find that database thet why it left it, then it gets testy
            try
            {
                var updateDBInit = new MigrateDatabaseToLatestVersion<ApplicationDBContext, Configuration>();
                updateDBInit.InitializeDatabase(db);
            }
            catch (Exception e)
            {
            }
            //Init Security
            //NOTE: Entity Framework MUST update the database BEFORE this WebSecurity block.
            //  If Entity Framework does not find that database thet why it left it, then it gets testy

            try
            {
                if (!WebSecurity.Initialized)
                {
                    WebSecurity.InitializeDatabaseConnection("ApplicationDBContext", "UserProfile", "UserId", "UserName",
                        autoCreateTables: true);
                }
            }
            catch (Exception e)
            {
            }

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

            //Init IoC(unity)
            Bootstrapper.Initialise();

            //Remove all but the Razor View Engine for some extra Perf
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            //Load Tax Periods into globaly available static structure
            TaxPeriods.Load();
        }
Beispiel #34
0
        public void Migrate <TDbContext, TConfiguration>(string nameOrConnectionString, Assembly migrationAssembly, Action <string> logger)
            where TDbContext : DbContext
            where TConfiguration : DbMigrationsConfiguration <TDbContext>, new()
        {
            logger($"MigrationStrategy: DbContext starting for {typeof(TDbContext).GetTypeInfo().Name}...");

            using (IScopeResolver scope = _resolver.BeginScope())
            {
                var dbContext     = scope.Resolve <TDbContext>(new { nameOrConnectionString });
                var dbInitializer = new MigrateDatabaseToLatestVersion <TDbContext, TConfiguration>(true, new TConfiguration());

                dbInitializer.InitializeDatabase(dbContext);
            }

            logger($"MigrationStrategy: DbContext finished succesfully for {typeof(TDbContext).GetTypeInfo().Name}.");
        }
 public void SetupDatabase()
 {
     var x = new MigrateDatabaseToLatestVersion<TeleConsultContext, DataConfiguration>();
     Database.SetInitializer(x);
     x.InitializeDatabase(new TeleConsultContext());
 }
 public static void Initialize()
 {
     var initializeMigrations =
         new MigrateDatabaseToLatestVersion<MyDataContext, Migrations.Configuration>();
     initializeMigrations.InitializeDatabase(new MyDataContext());
 }