Automatically create database

Personnally I’ve written a little helper function which create the database at startup using System.Data.SqlClient.

private string GetHangfireConnectionString()
        {
            string dbName = SettingsHelper.HangfireDbName;
            string connectionStringFormat = SettingsHelper.HangfireConnectionString;

            using (var connexion = new SqlConnection(string.Format(connectionStringFormat, "master")))
            {
                connexion.Open();

                using (var command = new SqlCommand(string.Format(
                    @"IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'{0}') 
                                    create database [{0}];
                      ", dbName), connexion))
                {
                    command.ExecuteNonQuery();
                }
            }

            return string.Format(connectionStringFormat, dbName);
        } 

Then during startup

var connectionString = GetHangfireConnectionString();
GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString);
1 Like