Database Creation with DbUp

This is going to be a quick post to show how to configure DbUp to create a new database on top of the migration functionality we have covered in the past. Use the following post to catch up on the DbUp topics we have covered in the past.

Database Migrations with DbUp
Code-based Database Migrations with DbUp
Always Run Migrations with DbUp
Logging Script Output with DbUp
Migrations in Transactions with DbUp

Database Creation

The code for database creation is a one-liner that just needs a connection string and should be run before any migrations. The following is part of our Main function for the sample application we have been working with with the EnsureDatabase line added and highlighted which is the code that takes care of database creation.

static int Main(string[] args)
    var connectionString =
        ?? "Server=localhost; Database=WideWorldImporters; Trusted_connection=true";


    var upgrader =
                                                           f => !f.Contains(".AlwaysRun."))

    var result = upgrader.PerformUpgrade();

Wrapping Up

As you can see it is simple to add the ability to create databases in your DbUp applications. Database creation in the official DbUp docs is just a note and is easy to miss so I wanted to do a post to call it out as it is a powerful feature when you need it. In our example, the application will always attempt to create the database if it doesn’t exist, but if that doesn’t fit your use case it might be worth wrapping database creation in an argument so the user could decide if the database should be created or not.

Also published on Medium.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.