We left Russia. We are against aggression and war with Ukraine. It is a tragedy for our nations, it is a nightmare

Automatically create database

How can I have the Hangfire database created automatically? I know it will create the schema & tables, but I’d like the database itself to be created if it doesn’t exist. This removes a manual step as part of deployments.

If you are using Entity Framework you can use Database.Migrate() in your DbContext.

Thanks for the response @Mercury.

Is the Hangfire DbContext exposed? What namespace is it in? Or are you suggesting creating a “dummy” DbContext specifically to be able to call Migrate?

@alelefant Did you ever figure this problem out? If so, what was your solution?

@Matt_Alexander Nope. It doesn’t seem like there’s a configurable way of doing this without rolling something yourself. We ended up creating the database manually.

Thanks @alelefant that’s what I ended up doing to.

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")))

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

            return string.Format(connectionStringFormat, dbName);

Then during startup

var connectionString = GetHangfireConnectionString();
1 Like

Exactly what I needed. Thanks.