public DatabaseRegistry() { var nHibernateConfiguration = new EmployeeApplicationNHibernateConfiguration(); //string connectionString = ConfigurationManager.ConnectionStrings["EmployeeApplicationContext"].ConnectionString; ISessionFactory sessionFactory = Fluently .Configure() .Database(SQLiteConfiguration.Standard.UsingFile(@"sqlite.db")) //.Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)) .Mappings(m => m.AutoMappings .Add(AutoMap.AssemblyOf<Employee>(nHibernateConfiguration)) ) .ExposeConfiguration(cfg => { var schemaExport = new SchemaExport(cfg); schemaExport.Drop(true, true); schemaExport.Create(true, true); }) .BuildSessionFactory(); For<ISessionFactory>().Singleton().Use(sessionFactory); For<ISession>().HybridHttpOrThreadLocalScoped().Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()); //TODO: Handle Tansactions For Application //For<IUnitOfWork>().CacheBy(new HybridLifecycle()).Use<UnitOfWork>(); }
public string Create() { var schemaExport = new SchemaExport(configuration); databaseProvider.CreateIfNotExists(); var stringBuilder = new StringBuilder(); schemaExport.Create(x => stringBuilder.Append(x), false); var statement = stringBuilder.ToString(); statement = string.IsNullOrWhiteSpace(statement) ? null : statement; if (!databaseProvider.Exists()) { databaseProvider.Create(); schemaExport.Execute(false, true, false); } else { try { new SchemaValidator(configuration).Validate(); } catch { schemaExport.Execute(false, true, false); } } return statement; }
public NewsManagementInMemoryDatabaseFactory(ProvideInMemoryNewsManagementSessionFactoryInitialisation provideSessionFactoryInitialisation) : base(provideSessionFactoryInitialisation) { provideSessionFactoryInitialisation.InitialiseSessionFactory(); SchemaExport export = new SchemaExport(provideSessionFactoryInitialisation.Configuration); export.Execute(true, true, false, Session.Connection, null); }
public void CriarSchema() { // Apenas no Init da Aplicação var config = new Configuration(); config.DataBaseIntegration(c => { c.Dialect<MsSql2012Dialect>(); c.ConnectionStringName = "ExemploNH"; c.LogFormattedSql = true; c.LogSqlInConsole = true; c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; }); var modelMapper = new ModelMapper(); modelMapper.AddMappings(typeof (ProdutoMap).Assembly.GetExportedTypes()); config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain"); ISessionFactory sessionFactory = config.BuildSessionFactory(); // NOTE: Estudar framework FluentMigration var schemaExport = new SchemaExport(config); schemaExport.Create(true, true); }
public void First_we_need_a_schema_to_test() { var schemaExport = new SchemaExport(_cfg); schemaExport.Drop(true, true); schemaExport.Create(true, true); try { using (IUnitOfWork work = UnitOfWork.Start()) using (ITransaction transaction = work.BeginTransaction(IsolationLevel.Serializable)) { using (var repository = new NHibernateRepository()) { repository.Save(new TestSaga(_sagaId) { Name = "Joe" }); repository.Save(new TestSaga(CombGuid.Generate()) { Name = "Chris" }); work.Flush(); transaction.Commit(); } } } finally { UnitOfWork.Finish(); } }
//�������ݿ� public static void CreateDataBase(string AssemblyName) { cfg = new Configuration(); cfg.AddAssembly(AssemblyName); SchemaExport sch = new SchemaExport(cfg); sch.Create(true, true); }
private static void BuildSchema() { NHibernate.Cfg.Configuration cfg = NHibernateConfigurator.Configuration; var schemaExport = new SchemaExport(cfg); schemaExport.Create(false, true); // A new session is created implicitly to run the create scripts. But this new session is not the context session }
protected void Application_Start() { new Configurator().StartServer<Configurator>(); var cfg = Simply.Do.GetNHibernateConfig(); var check = new SchemaValidator(cfg); try { check.Validate(); } catch { var exp = new SchemaExport(Simply.Do.GetNHibernateConfig()); exp.Drop(true, true); exp.Create(true, true); using (Simply.Do.EnterContext()) { UserSample.Init(); GroupSample.Init(); } } RegisterRoutes(RouteTable.Routes); }
public static IDbConnection BuildSchema(ISession Session, Configuration configuration) { var export = new SchemaExport(configuration); var connection = Session.Connection; export.Execute(true, true, false, connection, null); return connection; }
/// <summary> /// Creates new instance of <see cref="SQLiteInMemoryTestHelper"/> on top of supplied Configuration /// </summary> /// <param name="configuration"></param> public SQLiteInMemoryTestHelper(Configuration configuration) { _configuration = configuration; _sessionFactory = configuration.BuildSessionFactory(); _schemaExport = new SchemaExport(_configuration); }
public HelloWorldStructureMapRegistry() { IncludeRegistry<ProAceCoreRegistry>(); var sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("HelloWorld")).ShowSql()) .Mappings(m => { m.FluentMappings.AddFromAssemblyOf<MapMarker>(); m.FluentMappings.Conventions.AddFromAssemblyOf<CollectionAccessConvention>(); }) .ExposeConfiguration(cfg => { var schemaExport = new SchemaExport(cfg); schemaExport.Drop(true, true); schemaExport.Create(true, true); For<NHibernate.Cfg.Configuration>().Use(cfg); }) .BuildSessionFactory(); For<ISessionFactory>() .Singleton() .Use(sessionFactory); For<ISession>() .Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()); For<IUserRepository>().Use<UserRepository>(); }
private void btnGenerateDBScript_Click(object sender, RoutedEventArgs e) { Assembly assembly = Assembly.LoadFrom(txtFileName.Text); IPersistenceConfigurer databaseConfig = null; string fileName = "Domain Database Script - {0}.sql"; if (rdbSqlServer.IsChecked != null) if (rdbSqlServer.IsChecked.Value) { databaseConfig = MsSqlConfiguration.MsSql2005; fileName = string.Format(fileName, "Sql Server 2005"); } else if (rdbOracle.IsChecked != null) if (rdbOracle.IsChecked.Value) { databaseConfig = OracleDataClientConfiguration.Oracle9; fileName = string.Format(fileName, "Oracle 9g"); } Fluently.Configure() .Mappings(m => m.FluentMappings.AddFromAssembly(assembly)) .Database(databaseConfig)//.ConnectionString("Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True")) .ExposeConfiguration(config => { SchemaExport se = new SchemaExport(config); se.SetOutputFile(fileName); se.Create(false, false); MessageBox.Show(string.Format("Script successful created! See the '{0}' file.", fileName)); }).BuildConfiguration(); }
private void BuildSchema(Configuration config) { SchemaExport schema = new SchemaExport(config); schema.Drop(this._criaScript, this._exportaScriptBD); schema.Create(this._criaScript, this._exportaScriptBD); config.SetInterceptor(new SqlStatementInterceptor()); }
/// <summary> /// Initiate NHibernate Manager /// </summary> /// <param name="connect">NHibernate dialect, driver and connection string separated by ';'</param> /// <param name="store">Name of the store</param> public NHibernateManager(string connect, string store) { try { ParseConnectionString(connect); //To create sql file uncomment code below and write the name of the file SchemaExport exp = new SchemaExport(configuration); exp.SetOutputFile("db_creation.sql"); exp.Create(false, true); sessionFactory = configuration.BuildSessionFactory(); } catch (MappingException mapE) { if (mapE.InnerException != null) Console.WriteLine("[NHIBERNATE]: Mapping not valid: {0}, {1}, {2}", mapE.Message, mapE.StackTrace, mapE.InnerException.ToString()); else m_log.ErrorFormat("[NHIBERNATE]: Mapping not valid: {0}, {1}", mapE.Message, mapE.StackTrace); } catch (HibernateException hibE) { Console.WriteLine("[NHIBERNATE]: HibernateException: {0}, {1}", hibE.Message, hibE.StackTrace); } catch (TypeInitializationException tiE) { Console.WriteLine("[NHIBERNATE]: TypeInitializationException: {0}, {1}", tiE.Message, tiE.StackTrace); } }
public static void GenerateSchema(Configuration configuration) { //SchemaExport creates the database schema as defined in the mappings files. There must already be a database as defined in the App.Config file. SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.Create(true, true); }
public void SessionExtensions_Usage_WorkingIsCorrect() { var configuration = Fluently.Configure(); configuration.InitializeFromConfigSqLiteInMemory(true); configuration.AddMappingsFromAssemblyOf<UserMap>(); Configuration config = null; configuration.ExposeConfiguration(c => config = c); var factory = configuration.BuildSessionFactory(); var session = factory.OpenSession(); var export = new SchemaExport(config); export.Execute(false, true, false, session.Connection, null); Assert.IsNull(session.GetObject<User>(x => x.Name == "test")); session.Save(new User { Name = "test" }); session.Flush(); var user = session.GetObject<User>(x => x.Name == "test"); Assert.IsNotNull(user); user.Name = "foo"; session.Update(user); session.Flush(); user = session.GetObject<User>(x => x.Name == "foo"); Assert.IsNotNull(user); session.Delete(user); session.Flush(); Assert.IsNull(session.GetObject<User>(x => x.Name == "foo")); }
private static void CreateSchema(Configuration cfg) { var schemaExport = new SchemaExport(cfg); schemaExport.Drop(false, true); schemaExport.Create(false, true); cfg.SetProperty(NHibernate.Cfg.Environment.CurrentSessionContextClass, "web"); }
private void BuildSchema(Configuration cfg) { var schemaExport = new SchemaExport(cfg); schemaExport.Drop(script: false, export: true); schemaExport.Create(script: false, export: true); }
private static ISessionFactory BuildTestSessionFactory() { var testDatabaseConnectionString = "LocalDB"; var config = DatabaseConfiguration.Configure(testDatabaseConnectionString); /* * Need to comment these out when not needed because session factory can only be created once. * Database schemas need to be created BEFORE NHibernate schema export. * This needs to be run only once. */ /* var fac = DatabaseConfiguration.BuildSessionFactory(config); CreateSchemas(fac);*/ // Drop old database if any, create new schema config.ExposeConfiguration(cfg => { var export = new SchemaExport(cfg); //export.SetOutputFile(@"C:\Temp\vdb.sql"); export.Drop(false, true); export.Create(false, true); }); var fac = DatabaseConfiguration.BuildSessionFactory(config); FinishDatabaseConfig(fac); return fac; }
private static void ExportSchema(Configuration config) { var schema = new SchemaExport(config); // Auf false setzen, wenn kein neuer Account flushSchema = true; schema.Create(true, true); }
protected virtual Configuration FluentlyConfigureSqlite(SqliteDatabase database) { var filePath = database.FilePath; SQLiteConfiguration liteConfiguration = SQLiteConfiguration.Standard .UsingFile(filePath) .ProxyFactoryFactory(typeof(ProxyFactoryFactory)); var fluentConfig = Fluently .Configure() .Database(liteConfiguration) .Mappings(m => m.FluentMappings.AddFromAssembly(GetType().Assembly)) // Install the database if it doesn't exist .ExposeConfiguration(config => { if (File.Exists(filePath)) return; SchemaExport export = new SchemaExport(config); export.Drop(false, true); export.Create(false, true); }) .BuildConfiguration(); AddProperties(fluentConfig); return fluentConfig; }
protected void btnAddSchema_Click(object sender, EventArgs e) { Configuration cfg = GetCfg(); SchemaExport export = new SchemaExport(cfg); export.Create(false, true); lblStatus.Text = "Schema created"; }
public static ISessionFactory GetSessionFactory(SqlConnect sqlConnectProvider) { ISessionFactory factory = null; if (_cacheSessionFactory.TryGetValue(sqlConnectProvider.Name, out factory)) return factory; lock (_lockObj) { if (_cacheSessionFactory.TryGetValue(sqlConnectProvider.Name, out factory)) return factory; FluentConfiguration config = Fluently.Configure(); SetDefaultConfig(config); // if (conn.ProviderName.IndexOf("System.Data.SqlClient", StringComparison.OrdinalIgnoreCase) > -1) BuildMsSqlDatabase(config, sqlConnectProvider.ConnectionString); config.ExposeConfiguration(cfg => { cfg.SetProperty("command_timeout", "120"); var export = new SchemaExport(cfg).SetOutputFile(Path.Combine(PathHelper.AppDataPath, "myDDL.sql")); export.Create(true, false); }); factory= config.BuildSessionFactory(); _cacheSessionFactory[sqlConnectProvider.Name]=factory; } return factory; }
static void Main(string[] args) { //var assemblyNames = ConfigurationManager.AppSettings["nhibernate.assemblies"]; //if (assemblyNames.IsNullOrEmpty()) // throw new ConfigurationErrorsException("value required for nhibernate.assemblies, comma seperated list of assemblies"); //var config = new NHibernate.Cfg.Configuration(); //config.Configure(); //foreach (MappingAssembly assembly in TitanConfiguration.Instance.MappingAssemblies) // config.AddAssembly(assembly.Name); TitanFramework.Data.NHib.NHibernateHelper.InitialIze(); var config = TitanFramework.Data.NHib.NHibernateHelper.Configuration; var rebuildDatabase = ConfigurationManager.AppSettings["nhibernate.rebuilddatabase"]; if (TitanFramework.Extensions.StringExtensions.IsNullOrEmpty(rebuildDatabase)) throw new ConfigurationErrorsException("value required for nhibernate.assemblies, comma seperated list of assemblies"); switch (rebuildDatabase.ToLower()) { case "rebuild": var schemaExport = new SchemaExport(config); schemaExport.Drop(false, true); schemaExport.Execute(true, false, false); break; case "update": var schemaUpdate = new SchemaUpdate(config); schemaUpdate.Execute(true, true); break; } }
public void SchemaNamingConventionCustomNameTest() { var entities = new List<Type>() { typeof(City), typeof(State), typeof(ZipCode) }; Firehawk.Init() .Configure() .ConfigureMappings() .SearchForMappingsOnThisAssembly(Assembly.GetExecutingAssembly()) .EndConfig() .ConfigureEntities() .AddBaseEntity<Entity>() .AddEntities(entities) .EndConfig() .ConfigureNamingConventions() .UseCustomConventionForSchemaNames(t => "entities") .EndConfig() .EndConfiguration() .BuildMappings(NHConfig); var schemaExport = new SchemaExport(NHConfig); var tables = GetTables(); Assert.IsTrue(tables.Count == 3); Assert.IsTrue(tables.Any(t => t.Schema == "entities" && t.Name == "City")); Assert.IsTrue(tables.Any(t => t.Schema == "entities" && t.Name == "State")); Assert.IsTrue(tables.Any(t => t.Schema == "entities" && t.Name == "ZipCode")); }
public void CreateDB() { SchemaExport schemaExport = new SchemaExport(Common.GetNHibernateConnnectInfo()); schemaExport.Execute(false, true, false); CreateBlog(); }
private SchemaExport CreateSchemaExport(Configuration config) { var result = new SchemaExport(config); if (!string.IsNullOrEmpty(this.delimiter)) result.SetDelimiter(this.delimiter); if (!string.IsNullOrEmpty(this.outputFile)) result.SetOutputFile(this.outputFile); return result; }
public NHibernateRegistry() { Configuration cfg = Fluently.Configure() .Database(SQLiteConfiguration.Standard.UsingFile("database.db")) .Mappings(m => m.AutoMappings .Add(AutoMap .AssemblyOf<ProductDetailViewModel>() .Conventions .Add(new ClassConvention()))) .BuildConfiguration(); cfg.SetProperty(Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName); cfg.SetProperty(Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName); var export = new SchemaExport(cfg); export.Drop(true,true); export.Create(true,true); ISessionFactory sessionFactory = cfg.BuildSessionFactory(); ForRequestedType<Configuration>().AsSingletons() .TheDefault.IsThis(cfg); ForRequestedType<ISessionFactory>().AsSingletons() .TheDefault.IsThis(sessionFactory); ForRequestedType<ISession>().CacheBy(InstanceScope.Hybrid) .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()); ForRequestedType<IUnitOfWork>().CacheBy(InstanceScope.Hybrid) .TheDefaultIsConcreteType<UnitOfWork>(); ForRequestedType<IDatabaseBuilder>() .TheDefaultIsConcreteType<DatabaseBuilder>(); }
/// <summary> /// Creata data base /// </summary> /// <returns><see cref="DataBase"/></returns> public DataBase Create() { var database = Connection.Database; Connection.ConnectionString = GetConnectionString(); if (Dialect is MySQLDialect) { ExecuteCommand(string.Format("CREATE DATABASE IF NOT EXISTS {0};", database), Connection); } else if (Dialect is MsSql2000Dialect) { ExecuteCommand(string.Format("IF NOT(EXISTS(SELECT * FROM sys.sysdatabases where name='{0}')) BEGIN CREATE DATABASE {0}; END", database), Connection); } else if (Dialect is PostgreSQLDialect) { Connection.ChangeDatabase("postgres"); ExecuteCommand(string.Format("CREATE DATABASE {0};", database), Connection); } Connection = ConnectionFactory.Factory(Configuration, Dialect); var schemaExport = new SchemaExport(SessionManager.Configuration); schemaExport.Create(false, true); return this; }
public SqlLiteBuilder() { var showSql = GetShowSql(); var configuration = new Configuration() .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>()) .DataBaseIntegration(db => { db.Dialect<SQLiteDialect>(); db.Driver<SQLite20Driver>(); db.ConnectionString = "data source=:memory:"; }) .SetProperty(Environment.ReleaseConnections, "on_close") .SetProperty(Environment.ShowSql, showSql) .AddAssembly(Assembly.GetCallingAssembly()); _sessionFactory = Fluently.Configure(configuration) .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<SqlLiteBuilder>()) .BuildSessionFactory(); _session = _sessionFactory.OpenSession(); var textWriter = GetTextWriter(); var schemaExport = new SchemaExport(configuration); schemaExport.Execute(false, true, false, _session.Connection, textWriter); }
public NHibernate.Cfg.Configuration GetConfiguration() { if (_configuration != null) { return(_configuration); } var cfg = new NHibernate.Cfg.Configuration(); { cfg.Configure(@"OrmNhib/NHibernateConfig/hibernate.cfg.xml"); foreach (var mapping in cfg.ClassMappings) { string x = $"(1) {mapping.ClassName}, (2) {mapping.Discriminator}, (3) {mapping.DiscriminatorValue}, (4) {mapping.IsDiscriminatorValueNotNull}"; System.Diagnostics.Debug.WriteLine(x); } var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg); schemaExport.SetOutputFile(@"db.Postgre.sql").Execute( useStdOut: true, execute: true, justDrop: false); // Alternately, we can use SchemaUpdate.Execute, as in done in 1P NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg); schemaUpdate.Execute(useStdOut: true, doUpdate: true); try { SchemaValidator schemaValidator = new SchemaValidator(cfg); schemaValidator.Validate(); } catch (Exception ex) { Debug.WriteLine($"Exception: {ex}"); } // Note // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement // to tell the diff in schema, and only this got executed: /* * alter table Movie * add column NewProp VARCHAR(255) * * */ // // However, it does not work as expected all the times, for eg, // if I rename a column in HBM, it just adds a new column with new name // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged // So we will need manual scripts for migration // } _configuration = cfg; return(_configuration); }
internal static string ExportReadModelSchema(ReadModelConnectionString connectionString) { SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(buildConfig(connectionString)); StringBuilder data = new StringBuilder(); schema.Create((a) => { data.AppendLine(a); }, false); return(data.ToString()); }
internal static void CreateReadModelSchema(ReadModelConnectionString connectionString) { bool schemaCreated = false; if (!schemaCreated) { SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(buildConfig(connectionString)); schema.Create(true, true); schemaCreated = true; } }
public static void CreatSchema(string OutputFile, string ConnString) { FNHMVC.Data.Infrastructure.ConnectionHelper.GetConfiguration(ConnString).ExposeConfiguration(cfg => { var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg); if (!string.IsNullOrEmpty(OutputFile)) { schemaExport.SetOutputFile(OutputFile); } schemaExport.Drop(false, true); schemaExport.Create(false, true); }).BuildConfiguration(); }
public string ExportSchema() { var sqlBuilder = new StringBuilder(); var types = (from type in TypeEnumerator.Types where typeof(Entity).IsAssignableFrom(type) && type != typeof(Entity) select type); Configure(types, ""); var export = new NHibernate.Tool.hbm2ddl.SchemaExport(Configuration); export.Execute(s => sqlBuilder.AppendLine(s + ";"), false, false); return(sqlBuilder.ToString()); }
public void GenerateDatabase() { SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(LocalSessionFactoryObject.Configuration); schemaExport.Create(true, true); }