Categories
Uncategorized

Automatically Apply EF Core Database Migrations in Azure Function App on Startup

To apply database migrations to an Azure Function app on startup, you’ll need to have the following set up first:

Once the above is set up, you can set up the application to apply all migrations on startup, making for a link between the running application and the database it is dependent on. This is especially useful for local development – as you won’t run into cases where a local schema is outdated.

Add the following code to the Startup.cs file:

...

[assembly: FunctionsStartup(typeof(YOUR_NAMESPACE.Startup))]

namespace YOUR_NAMESPACE
{
  class Startup : FunctionsStartup
  {
    public override void Configure(IFunctionsHostBuilder builder)
    {
      ConfigureDatabase(builder);
      ...
    }

    private void ConfigureDatabase(IFunctionsHostBuilder builder)
    {
      string SqlConnection =
                    Environment.GetEnvironmentVariable(
                      Constants.ConnectionStringKey);

      if (SqlConnection == null)
      {
        throw new ArgumentNullException(
          $"Environment variable {Constants.ConnectionStringKey} not set.");
      }

      builder.Services.AddDbContext<Context>(
        options => options.UseSqlServer(SqlConnection));

      var optionsBuilder = new DbContextOptionsBuilder<Context>();
      optionsBuilder.UseSqlServer(SqlConnection);

      using (var context = new Context(optionsBuilder.Options))
      {
        try
        {
          context.Database.Migrate();
        }
        catch (Exception e)
        {
          throw new Exception(
            $"Error when migrating database: {e.Message}");
        }
      }
    }
  }
}

Leave a Reply

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