• Max Morrow

Automate Database Deployments With Entity Framework Core

Having worked with a variety of different database deployment strategies, I've started to really enjoy using Entity Framework Core as a primary method of SQL deployment automation for a few reasons. First and foremost, if you're using Entity Framework and packaging your application using Docker now, it's relatively easy to automate your database deployments. Let's dive in and take a look at how it works.


NOTE:

  • We're going to be talking about this automation in the context of an existing deployment pipeline.

  • To better focus on automated database deployments, we'll also be assuming that you already have EF Core set up within your application.


Application Stack

Before we begin, let's talk about the application stack we'll be working with. This example is using:

  • .NET Core 3.1

  • Web API

  • Entity Framework Core

You can find the completed example solution here:


Setting Things Up: That's Right, Two Steps

  1. The only change you'll need to make is within your Startup.cs file. Head to the bottom of the Configure method and add:

         using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
         {
            var dbContext = scope.ServiceProvider.GetService<DatabaseContext>();
            var pendingMigrations = dbContext.Database.GetPendingMigrations().Any();
            if (pendingMigrations)
            {
               dbContext.Database.Migrate();
            }
         }        

2. Start the project and your migrations will execute on startup (as long as one is pending)


Deployment: No Changes

The good news is, you won't have to make any changes to your CI/CD pipelines. With your application configured to run the migrations on start-up, when you deploy your application, the migrations will automatically be applied.

144 views0 comments