user9128740
user9128740

Reputation:

How to apply code first migration to a database in Azure?

I'm developing ASP.NET Core API app which I have hosted in Azure. The development and deployment has been all smooth, but I have a problem when I need to apply a migration.

When I develop I use a local SQL database, and when deployed I rely on an Azure SQL database. I'm providing the connection string through user secrets in development, and for the production I use the Azure Key Vault to read the connection string. And of course, there is the ASPNETCORE_ENVIRONMENT environment variable which I keep as Development while I develop and change to Production once I deploy to Azure. But, the problem is that no matter whether my ASPNETCORE_ENVIRONMENT variable is set to Development or Production, when I create a new migrations when developing and issue dotnet ef update database from PowerShell, it just updates my local database, and my Azure database is not changed. Any ideas how can I issue a migration to my database that is in Azure?

Upvotes: 1

Views: 549

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13498

public void ConfigureServices(IServiceCollection services)
{            
     services.AddDbContext<MyContext>(
         options => options.UseSqlServer(
              Configuration.GetConnectionString("DefaultConnection")));
}

public void Configure(
     IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
     if (env.IsProduction())
         using (var context = serviceProvider.GetService<MyContext>())
             context.Database.Migrate();
}

Upvotes: 2

Related Questions