Create Database using Fluent Nhibernate

1

Is there any way to create a new database directly from my application? I'm using Asp.Net MVC5 C #, Fluent Nhibernate and PostgreSQL.

Note: I can already access my tables through the application, what I need is to generate a new database through the application.

    
asked by anonymous 10.01.2018 / 18:43

2 answers

0

Nhibernate does not generate a new Database, however it is possible to generate new DBs by adding the Npgsql reference.

With this we can now execute:

// 1. Connect to server to create database:
const string connStr = "Server=localhost;Port=5432;User Id=postgres;Password=enter;";

// 2. Connect to server to create table:
const string connStr2 = "Server=localhost;Port=5432;User Id=postgres;Password=enter;Database=testDb";


var m_conn = new NpgsqlConnection(connStr); // db connction
var m_conn2 = new NpgsqlConnection(connStr2); // table connection

// creating a database in Postgresql
m_createdb_cmd = new NpgsqlCommand("CREATE DATABASE IF NOT EXISTS  \"testDb\" " +
                               "WITH OWNER = \"postgres\" " +
                               "ENCODING = 'UTF8' " +
                               "CONNECTION LIMIT = -1;", m_conn);

// creating a table in Postgresql
m_createtbl_cmd = new NpgsqlCommand
   {
   CommandText ="CREATE TABLE table1(ID CHAR(256) CONSTRAINT id PRIMARY KEY, Title CHAR)"
   };

   m_createtbl_cmd.Connection = m_conn2;

 // 3.. Make connection and create

    // open connection to create DB
    m_conn.Open();
    m_createdb_cmd.ExecuteNonQuery();
    m_conn.Close();

    // open connection to create table
    m_conn2.Open();
    m_createtbl_cmd.ExecuteNonQuery();
    m_conn2.Close();
    
19.09.2018 / 20:28
1

I use this way:

private static FluentConfiguration Configure()
        {
            return Fluently.Configure()
                        .ExposeConfiguration(x => {
                            x.SetProperty("current_session_context_class", "web");
                            x.SetProperty("generate_statistics", "true");
                        })
                        .Database(MsSqlConfiguration.MsSql2008
                                        .ConnectionString(c => c.FromConnectionStringWithKey("Conexao"))
                                        #if DEBUG
                                        .ShowSql()
                                        #endif
                                        )
                                        .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(MapCidade).Assembly));
        }

/// <summary>
/// Método utilizado para criar o Banco de Dados do Sistema.
/// </summary>
public static void GenerateDatabase()
{
    var c = Configure();
    c.ExposeConfiguration(cfg => new SchemaExport(cfg)
     .Create(false, true))
     .BuildConfiguration();
}

Remember to put usings to fluent.

    
10.01.2018 / 18:48