protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); var context = new DREAMContext(); var initializeDomain = new CreateDatabaseIfNotExists<DREAMContext>(); var initializeMigrations = new MigrateDatabaseToLatestVersion<DREAMContext, Configuration>(); //initializeDomain.InitializeDatabase(context); //initializeMigrations.InitializeDatabase(context); //using (FSDirectory d = FSDirectory.Open(new DirectoryInfo(SearchIndex.DirPath))) //{ // SearchAutoComplete sac = new SearchAutoComplete(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/SearchAutocompleteIndex"); // sac.BuildAutoCompleteIndex(d, "Keywords"); //} Database.SetInitializer(new MigrateDatabaseToLatestVersion<DREAMContext, Configuration>()); #if DEBUG && FALSE Database.SetInitializer(new DREAM.Models.DREAMContextInitializer()); #endif }
/// <summary> /// 数据库初始化,自动迁移到最新版本 /// </summary> public static void Initialize <TContext, TMigrationsConfiguration>(Action <TContext> callback = null) where TContext : DbContext, new() where TMigrationsConfiguration : DbMigrationsConfiguration <TContext>, new() { IDatabaseInitializer <TContext> initializer; var context = new TContext(); if (!context.Database.Exists()) { initializer = new CreateDatabaseIfNotExists <TContext>(); } else { initializer = new MigrateDatabaseToLatestVersion <TContext, TMigrationsConfiguration>(); } Database.SetInitializer(initializer); // 预先生成EF的映射视图 using (context) { PreMapping(context); if (callback != null) { callback(context); } } }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var initializer = new CreateDatabaseIfNotExists <StoreContext>(); Database.SetInitializer(initializer); }
static void Main(string[] args) { var dbInitializer = new CreateDatabaseIfNotExists <CodeFirstDbContext>(); dbInitializer.InitializeDatabase(new CodeFirstDbContext()); Console.Read(); }
public static ApplicationDbContext Create() { IDatabaseInitializer <ApplicationDbContext> strategy; switch (ConfigurationManager.AppSettings["Database_Initialize_Strategy"]) { case "CreateDatabaseIfNotExists": strategy = new CreateDatabaseIfNotExists <ApplicationDbContext>(); break; case "DropCreateDatabaseAlways": strategy = new DropCreateDatabaseAlways <ApplicationDbContext>(); break; case "DropCreateDatabaseIfModelChanges": strategy = new DropCreateDatabaseIfModelChanges <ApplicationDbContext>(); break; case "MigrateDatabaseToLatestVersion": strategy = new MigrateDatabaseToLatestVersion <ApplicationDbContext, Configuration>(); break; default: strategy = new NullDatabaseInitializer <ApplicationDbContext>(); break; } Database.SetInitializer(strategy); return(new ApplicationDbContext()); }
public void CreatedatabaseIfNotExists() { SqlConnection.ClearAllPools(); var initializer = new CreateDatabaseIfNotExists <MiamDbContext>(); Database.SetInitializer(initializer); }
public void CreatedatabaseIfNotExists() { SqlConnection.ClearAllPools(); var initializer = new CreateDatabaseIfNotExists<MiamDbContext>(); Database.SetInitializer(initializer); }
public ICoinManagerContext() { Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; var createIfNotExists = new CreateDatabaseIfNotExists <ICoinManagerContext>(); createIfNotExists.InitializeDatabase(this); }
/// <summary> /// 初始化一个<see cref="DbContextInitializerBase"/>类型的新实例 /// </summary> protected DbContextInitializerBase() { DatabaseInitializer = new CreateDatabaseIfNotExists <TDbContext>(); if (EnabledAutoMigrate) { DatabaseInitializer = new MigrateDatabaseToLatestVersion <TDbContext, AutoMigrationsConfiguration <TDbContext> >(); } }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove <PluralizingEntitySetNameConvention>(); modelBuilder.Conventions.Remove <PluralizingTableNameConvention>(); var initializer = new CreateDatabaseIfNotExists <FormulaIFSContext>(); Database.SetInitializer(initializer); }
public void Init() { IDatabaseInitializer <Model.BddContext> init = new CreateDatabaseIfNotExists <Model.BddContext>(); //IDatabaseInitializer<Model.BddContext> init = new DropCreateDatabaseAlways<Model.BddContext>(); //IDatabaseInitializer<Model.BddContext> init = new DropCreateDatabaseIfModelChanges<Model.BddContext>(); Database.SetInitializer(init); init.InitializeDatabase(new Model.BddContext()); }
private void Button_Click(object sender, RoutedEventArgs e) { IDatabaseInitializer <Model.BddContext> init = new CreateDatabaseIfNotExists <Model.BddContext>(); //IDatabaseInitializer<Model.BddContext> init = new DropCreateDatabaseAlways<Model.BddContext>(); //IDatabaseInitializer<Model.BddContext> init = new DropCreateDatabaseIfModelChanges<Model.BddContext>(); Database.SetInitializer(init); init.InitializeDatabase(new Model.BddContext()); }
public void Test01_Initialize_Database_Using_CreateDatabaseIfNotExists_Without_DataSeeder() { var dbContext = new FakeDbContext(); var initialiser = new CreateDatabaseIfNotExists(); initialiser.Initialize(dbContext); dbContext.ensureCreatedCalled.Should().BeTrue(); dbContext.ensureDeletedCalled.Should().BeFalse(); }
protected void Application_Start() { var initializer = new CreateDatabaseIfNotExists <ToDoListDbContext>(); Database.SetInitializer(initializer); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public static void initDb() { if (dbContext == null) { dbContext = new MailingAppDbContext(); } var initializer = new CreateDatabaseIfNotExists <MailingAppDbContext>(); initializer.InitializeDatabase(dbContext); }
/// <summary> /// Initializes a new instance of the <see cref="IntegrationTestContext"/> class. /// </summary> /// <param name="nameOrConnectionString">The name or connection string.</param> public IntegrationTestContext(string nameOrConnectionString) : base(nameOrConnectionString) { // Set the chosen database initializer and initialize the database IDatabaseInitializer<IntegrationTestContext> databaseInitializer = new CreateDatabaseIfNotExists<IntegrationTestContext>(); //IDatabaseInitializer<IntegrationTestContext> databaseInitializer = new DropCreateDatabaseIfModelChanges<IntegrationTestContext>(); //IDatabaseInitializer<IntegrationTestContext> databaseInitializer = new DropCreateDatabaseAlways<IntegrationTestContext>(); //IDatabaseInitializer<IntegrationTestContext> databaseInitializer = new TestDbInitializer<IntegrationTestContext>(); Database.SetInitializer(databaseInitializer); }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationDbContext"/> class. /// </summary> /// <param name="nameOrConnectionString">The name or connection string.</param> public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { // Set the chosen database initializer and initialize the database IDatabaseInitializer<ApplicationDbContext> databaseInitializer = new CreateDatabaseIfNotExists<ApplicationDbContext>(); Database.SetInitializer(databaseInitializer); // We do not need to explicitly instantiate all of the Stored // procedures properties using "this.InitializeStoredProcedureProperties();" // as this is carried out for us by the "Dibware.StoredProcedureFrameworkForEF.StoredProcedureDbContext" // class constructors }
/// <summary> /// Constructs a new <see cref="IntegrationTestDbContext" /> instance using the existing connection to connect to a database. /// The connection will not be disposed when the context is disposed if <paramref name="contextOwnsConnection" /> /// is <c>false</c>. /// </summary> /// <param name="existingConnection"> An existing connection to use for the new context. </param> /// <param name="contextOwnsConnection"> /// If set to <c>true</c> the connection is disposed when the context is disposed, otherwise the caller must dispose the connection. /// </param> public IntegrationTestDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { // Set the chosen database initializer and initialize the database IDatabaseInitializer<IntegrationTestDbContext> databaseInitializer = new CreateDatabaseIfNotExists<IntegrationTestDbContext>(); Database.SetInitializer(databaseInitializer); // We do not need to explicitly instantiate all of the Stored // procedures properties using "this.InitializeStoredProcedureProperties();" // as this is carried out for us by the "Dibware.StoredProcedureFrameworkForEF.StoredProcedureDbContext" // class constructors }
protected void Application_Start() { if (!Database.Exists("CountingKsConnectionString")) { CreateDatabaseIfNotExists <CountingKsContext> db = new CreateDatabaseIfNotExists <CountingKsContext>(); Database.SetInitializer(new CountingKsDbContextSeeder(new CountingKsContext())); } //GlobalConfiguration.Configuration.MessageHandlers.Add(new APIKeyMessageHandler()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public void Test05_Initialize_Database_Using_CreateDatabaseIfNotExists_With_DataSeeder_For_Existing_Database() { var dbContext = new AnotherFakeDbContext(); var dataSeederMock = new Mock <IDataSeeder>(); var initialiser = new CreateDatabaseIfNotExists(dataSeederMock.Object); initialiser.Initialize(dbContext); dbContext.ensureCreatedCalled.Should().BeTrue(); dbContext.ensureDeletedCalled.Should().BeFalse(); dataSeederMock.Verify(m => m.Seed(It.IsAny <DbContext>()), Times.Never); }
public void Saves_Successfully_WhenExternalTransactionUsed() { var initializer = new CreateDatabaseIfNotExists <BloggerDbContext>(); Database.SetInitializer(initializer); initializer.InitializeDatabase(new BloggerDbContext()); using (var conn = new SqlConnection(@"Server=.\SqlExpress;Database=Blog;Integrated Security=true;Trusted_Connection=true")) { conn.Open(); using (var sqlTxn = conn.BeginTransaction(IsolationLevel.ReadCommitted)) { using ( var dbContextScope2 = _dbContextScopeFactory.CreateAmbientDbContextWithExternalTransaction <BloggerDbContext>(sqlTxn, conn)) { //Get the current DbContext of type BloggerDbContext var context2 = DbContextLocator.GetDbContext <BloggerDbContext>(); //Adding Blog to the database. var blog2 = new Blog { CreatedDate = DateTime.Now, UpdatedDate = DateTime.Now, BlogUser = new User { Name = "TestUser", Occupation = "Software Developer", }, Overview = "This is a test overview" }; context2.Blogs.Add(blog2); var post = new Post { Content = "Test Content", Meta = "Test", ShortDescription = "This is an example test content", Title = "Ambient Simple Test Context" }; blog2.BlogPost = post; dbContextScope2.SaveAndCommitChanges(); Assert.That(context2.Blogs.Count() == 1); } sqlTxn.Commit(); } conn.Close(); conn.Dispose(); } }
public void ShouldResolveConcurrencyExceptionWithDatabaseWinsStrategy() { // Arrange var databaseInitializer = new CreateDatabaseIfNotExists <EmployeeContext>(); IConcurrencyResolveStrategy concurrencyResolveStrategy = new DatabaseWinsConcurrencyResolveStrategy(); var initialEmployee = Testdata.Employees.CreateEmployee1(); string firstNameChange1 = initialEmployee.FirstName + " from employeeContext1"; string firstNameChange2 = initialEmployee.FirstName + " from employeeContext2"; using (var employeeContext = this.CreateContext(databaseInitializer)) { employeeContext.Set <Employee>().Add(initialEmployee); employeeContext.SaveChanges(); } // Act using (var employeeContext1 = this.CreateContext(databaseInitializer)) { employeeContext1.ConcurrencyResolveStrategy = concurrencyResolveStrategy; // Get an employee (which has a Version Timestamp) in one context and modify var employeeFromContext1 = employeeContext1.Set <Employee>().First(p => p.Id == 1); employeeFromContext1.FirstName = firstNameChange1; // Modify and Save the same employee in another context to simulate concurrent access using (var employeeContext2 = this.CreateContext(databaseInitializer)) { var employeeFromContext2 = employeeContext2.Set <Employee>().First(p => p.Id == 1); employeeFromContext2.FirstName = firstNameChange2; employeeContext2.SaveChanges(); } // SaveChanges of the first context results in a DbUpdateConcurrencyException employeeContext1.SaveChanges(); } // Assert using (var employeeContext = this.CreateContext(databaseInitializer)) { var returnedEmployee = employeeContext.Set <Employee>().First(p => p.Id == 1); returnedEmployee.FirstName.Should().Be(firstNameChange2); } }
public ConnexionWindow() { RoutedCommand firstSettings = new RoutedCommand(); firstSettings.InputGestures.Add(new KeyGesture(Key.Enter, ModifierKeys.Alt)); CommandBindings.Add(new CommandBinding(firstSettings, OnOpenExistingButtonClicked)); InitializeComponent(); Title = "Connexion"; IDatabaseInitializer <DataBaseContext> init = new CreateDatabaseIfNotExists <DataBaseContext>(); //IDatabaseInitializer<DataBaseContext> init = new DropCreateDatabaseAlways<DataBaseContext>(); //IDatabaseInitializer<DataBaseContext> init = new DropCreateDatabaseIfModelChanges<DataBaseContext>(); Database.SetInitializer(init); init.InitializeDatabase(new DataBaseContext()); ListArchive.ItemsSource = NoteEncryptCSManager.GetInstance().GetArchives(); ListArchive.SelectedIndex = 0; }
public void InitializerDatabase() { var context = new DefaultDbContext(); IDatabaseInitializer <DefaultDbContext> initializer; if (!context.Database.Exists()) { initializer = new CreateDatabaseIfNotExists <DefaultDbContext>(); } else { initializer = new MigrateDatabaseToLatestVersion <DefaultDbContext, AutoMigrationsConfiguration <DefaultDbContext> >(); } Database.SetInitializer(initializer); ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; StorageMappingItemCollection mappingItemCollection = (StorageMappingItemCollection)objectContext.ObjectStateManager .MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappingItemCollection.GenerateViews(new List <EdmSchemaError>()); context.Dispose(); }
public static void CreateDatabaseFile(string path) { try { using (var sqLiteConnection = CreateConnection(path)) using (var context = new AfTestAppContext(sqLiteConnection)) { var initializator = new CreateDatabaseIfNotExists <AfTestAppContext>(); Database.SetInitializer(initializator); context.SaveChanges(); // do not delete this log trace. we need some DB touch //_log.Trace("Db Context validated. Found {0} Customer(s)", context.A1.Count()); } } catch (Exception ex) { Logger.Error(ex); } }
public void ShouldRethrowConcurrencyUpdateExceptionAsDefault() { // Arrange var databaseInitializer = new CreateDatabaseIfNotExists <EmployeeContext>(); var initialEmployee = Testdata.Employees.CreateEmployee1(); string firstNameChange1 = initialEmployee.FirstName + " from employeeContext1"; string firstNameChange2 = initialEmployee.FirstName + " from employeeContext2"; using (var employeeContext = this.CreateContext(databaseInitializer)) { employeeContext.Set <Employee>().Add(initialEmployee); employeeContext.SaveChanges(); } // Act using (var employeeContext1 = this.CreateContext(databaseInitializer)) { // Get an employee (which has a Version Timestamp) in one context and modify var employeeFromContext1 = employeeContext1.Set <Employee>().First(p => p.Id == 1); employeeFromContext1.FirstName = firstNameChange1; // Modify and Save the same employee in another context to simulate concurrent access using (var employeeContext2 = this.CreateContext(databaseInitializer)) { var employeeFromContext2 = employeeContext2.Set <Employee>().First(p => p.Id == 1); employeeFromContext2.FirstName = firstNameChange2; employeeContext2.SaveChanges(); } // SaveChanges of the first context results in a DbUpdateConcurrencyException Action action = () => employeeContext1.SaveChanges(); // Assert action.Should().Throw <DbUpdateConcurrencyException>(); } }
protected override void ProcessRecord() { base.ProcessRecord(); using (SimpleBlogDbContext context = new SimpleBlogDbContext(GetConnectionString())) { CreateDatabaseIfNotExists<SimpleBlogDbContext> databaseInitializer = new CreateDatabaseIfNotExists<SimpleBlogDbContext>(); databaseInitializer.InitializeDatabase(context); Author author = new Author { Name = Author }; context.Authors.Add(author); Settings settings = new Settings { BlogPageUrl = BlogPageUrl, Name = BlogName }; context.Settings.Add(settings); context.SaveChanges(); } }
public void InitializeDatabase(TContext context) { bool dbExists; try { using (new TransactionScope(TransactionScopeOption.Suppress)) { dbExists = context.Database.Exists(); } } catch { dbExists = false; } if (dbExists) { var databaseInitializerHelper = EngineContext.Current.Resolve <IKoreEntityFrameworkHelper>(); databaseInitializerHelper.EnsureTables(context); } else { //please don't remove this.. if you want it to work, then add "Persist Security Info=true" to your connection string. try { var defaultInitializer = new CreateDatabaseIfNotExists <TContext>(); defaultInitializer.InitializeDatabase(context); } catch (Exception x) { var logger = LoggingUtilities.Resolve(); logger.Error(x.Message, x); } } }
/// <summary> /// 初始化 /// </summary> public static void Init() { IDatabaseInitializer <MySqlDbContext> initializer; if (!Database.Exists(_nameOrConnectionString)) { //初始化代码放在CreateDatabaseIfNotExists中 //initializer = new CreateDatabaseIfNotExists<MySqlDbContext>(); initializer = new CreateDatabaseIfNotExists <MySqlDbContext>(); } else { //初始化代码不要放在MigrateDatabaseToLatestVersion中 //initializer = new MigrateDatabaseToLatestVersion<MySqlDbContext, MigrationConfiguration>(); //MySql的数据库迁移有bug,不能用 ////相当于null,不进行初始化 initializer = new NullDatabaseInitializer <MySqlDbContext>(); } // The database initializer is called when a the given System.Data.Entity.DbContext type is used to access a database for the first time. //因为第一次访问数据库时调用Seed来初始化,所以目前检查数据库是否存在并没有调用Seed Database.SetInitializer(initializer); }
internal QueueDataBaseContext(string connectionString, bool isConnectionName = true) : base(isConnectionName? "name=" + connectionString : connectionString) { dbInitializerStrategy = new CreateDatabaseIfNotExists <QueueDataBaseContext>(); Database.SetInitializer(dbInitializerStrategy); }
static void Main(string[] args) { var dbInitializer = new CreateDatabaseIfNotExists <MyDbContext>(); dbInitializer.InitializeDatabase(new MyDbContext()); }
public DataStoreService(string username) : base("Data") { this.username = username; string initType = ConfigurationManager.AppSettings["testDataInitializerType"]; IDatabaseInitializer<DataStoreService> initializer; if (string.IsNullOrWhiteSpace(initType)) { initializer = new CreateDatabaseIfNotExists<DataStoreService>(); } else { Type type = Type.GetType(initType); initializer = (IDatabaseInitializer<DataStoreService>)Activator.CreateInstance(type); } Database.SetInitializer<DataStoreService>(initializer); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); IDatabaseInitializer <Models.FestivalAPIContext> init = new CreateDatabaseIfNotExists <Models.FestivalAPIContext>(); }
internal QueueDataBaseContext() : base("name=DefaultConnection") { dbInitializerStrategy = new CreateDatabaseIfNotExists <QueueDataBaseContext>(); Database.SetInitializer(dbInitializerStrategy); }
public RepositoryContext() : base("ApiClienteConnection") { CreateDatabaseIfNotExists <RepositoryContext> db = new CreateDatabaseIfNotExists <RepositoryContext>(); db.InitializeDatabase(this); }
public override void SetDatabaseInitializer() { var initializer = new CreateDatabaseIfNotExists<CMSContext>(); Database.SetInitializer<CMSContext>(initializer); }
/// <summary> /// Création de la table "campagnes" si la table n'existe pas /// </summary> public static void CreateTable() { var initializer = new CreateDatabaseIfNotExists <ContextEf>(); initializer.InitializeDatabase(new ContextEf()); }