Search code examples
postgresqlnhibernatefluent-nhibernatehbm2ddl

Automatically create the schema in PostgreSQL with Fluent NHibernate


How to create the database schema automatically in Fluent Nhibernate? My configuration is:

  public static ISessionFactory CreateDatabase() {
  switch (4) {
    case 4: // Postgress
    _sessionFactory = Fluently.Configure()
      .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(ConnectionString))
      .ExposeConfiguration(c => {
        c.SetProperty("cache.use_second_level_cache", "false");
        c.SetProperty("cache.use_query_cache", "false");
      })
      .ExposeConfiguration(SchemaMetadataUpdater.QuoteTableAndColumns)
      .ExposeConfiguration(x => new SchemaUpdate(x).Execute(false, true))
      .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Pessoa>())
      .CurrentSessionContext<WebSessionContext>()
      .BuildConfiguration()
      .BuildSessionFactory();
    break;
  }
  _sessionFactory.Dispose();
  return _sessionFactory;
}

Currently have a method that creates using NpgsqlCommand.


Solution

  • To create the schema with NHibernate, you use the SchemaExport class:

    Configuration cfg = ....;
    new SchemaExport(cfg).Create(false, true);
    

    More details in the NHibernate reference, section 20.1.2. Running the tool, and the preceding section.