How to automatically keep your database up to date with Entity Framework

by John Nye

27 Sep
2013

I recently deployed a new test website to Windows Azure using Azure's Git integration. The problem I had is that I didn't want to drop and recreate the database each time I pushed a release (and lose my data), nor did I want to manually upgrade the database in Package Manager Console.

The solution (once found... hence the blog post) was simple.

In our DataContext we simply needed to set the initializer to migrate to the latest version. This is done as follows:

public class MyDataContext : DbContext
{
    public MyDataContext()
        :base("DefaultConnection")
    {            
    }

    // Context properties

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(
            new MigrateDatabaseToLatestVersion<MyDataContext, Configuration>());
        base.OnModelCreating(modelBuilder);
    }
}

It does exactly what it says on the tin (or class). When creating the data model, migrate the database to the latest version. Simples. The solution was clean and simple, it just took a bit of searching. Hopefully this blog will help you resolve the same issue I had.

And that's it. Every time I push to my release branch Azure pick's it up and releases it. When the app starts my database is brought right up to date using my data migrations. Brilliant!

Comments 0 * Be the first to comment!

Leave a message...

30 Mar
2017