Is it possible to create a database using NHibernate

databasefluent-nhibernatenhibernate

I am using NHibernate with FluentNHibernate for my DAL. I am also using SchemaExport and SchemaUpdate to create and update my database schema.

My problem is that the schema operations all require the database to exist before they will work. I want to programmatically create my database and update the schema as there may be multiple databases and the creating of the database is not only a once-off operation.

I know I can do this manually by executing a create database command on a connection to the master database, but this feels wrong considering that I otherwise use NHibernate for all my database interactions. As an aside, I use a SQLite inmemory database for my unit tests so any sql I write will then have to know which database I'm using.

Is there any way to get NHibernate to create my database for me?

Best Answer

I think that creating db with NHibernate is nice, if you start to develop application with domain model. I mean - it gives an insight how your db should look. But in general - sql scripts should be used.

I heard that some developers uses NHibernate db generation for integration tests, they create lightweight sqlite db on fly.

How to generate db with NHibernate? This is how i do that:

 public static void InitSessionFactory()
    {
        var connectionString =
            ConfigurationManager
                .ConnectionStrings["MyConnectionString"]
                .ConnectionString;

        var cfgFromXml = new Configuration();
        cfgFromXml.Configure();

        var cfg = Fluently.Configure(cfgFromXml)
            .Database(MsSqlConfiguration.MsSql2005
                          .ConnectionString(x => x.Is(connectionString))
                          .UseReflectionOptimizer())
            .Mappings(x => x.FluentMappings
                               .AddFromAssemblyOf<NHibernateBootstrapper>())
            .ExposeConfiguration(BuildSchema);


        ObjectFactory.Inject(cfg.BuildSessionFactory());
    }

    private static void BuildSchema(Configuration config)
    {
        //Creates database structure
        //new SchemaExport(config)
        //   .Create(false, true);
    }