DbUp is a .NET library that helps you to deploy changes to SQL Server databases. It tracks which SQL scripts have been run already, and runs the change scripts that are needed to get your database up to date.
Upgrading
If you are upgrading from version 3 to 4, see breaking changes. Other release notes are available in the GitHub releases.
Getting started
Create a simple console application
dotnet new console
dotnet add . package DbUp
Add your SQL scripts to it a directory (ex: Scripts
)
Modify the csproj
file to add the scripts as embedded resources
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<EmbeddedResource Include="scripts/**/*.sql" />
</ItemGroup>
</Project>
Finally, in Program.cs
, add the following code:
static int Main(string[] args)
{
var connectionString =
args.FirstOrDefault()
?? "Server=(local)\\SqlExpress; Database=MyApp; Trusted_connection=true";
var upgrader =
DeployChanges.To
.SqlDatabase(connectionString)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
.LogToConsole()
.Build();
var result = upgrader.PerformUpgrade();
if (!result.Successful)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(result.Error);
Console.ResetColor();
#if DEBUG
Console.ReadLine();
#endif
return -1;
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Success!");
Console.ResetColor();
return 0;
}
Note: If you want your application to create the database for you, add the following line after the connection string:
EnsureDatabase.For.SqlDatabase(connectionString);
This way it will check if the target database exist if not it will create the database and then run your scripts
You now have a console application that can run change scripts against your database! After running it, you'll see something like this:
The next time you run it, you'll see:
Why a console application?
By putting your migration scripts in an executable that can be run, you'll get a lot of benefits:
- You can hit F5 at any time to test the migration scripts
- Other developers on your team can do the same
- You can execute them as part of an automated deployment
- You can run it during your integration tests
- Since it's in your VS solution, it will go into source control along with the rest of your code
Alternatively, instead of a console application, you can create a class library that references DbUp, and embed it into a maintenance screen inside your application.
Check out this blog post to learn more about the philosophy behind DbUp.
Other ways to use DbUp
See usage