EntityFramework 7, migrations and ConnectionString

c# entity-framework-core

Question

I'm trying to create a simple web site using asp.net vnext and EF 7.0. For development I use localDB and migrations work well. Then I deploy my site to Azure and want to apply migrations to Azure SQL Server.

Is there any way to apply migrations to the production database, or how to change connection string dynamically for migrations apply?

Don't want to change the connection string every time I apply migrations.

Accepted Answer

There are 3 ways to apply migrations.

  1. Programmatically (outdated: see update below)

    context.Database.ApplyMigrations()
    
  2. From the command line. This is really meant for developers managing their local databases, not remote servers. As you noted, running against Azure would require your local project to contain a connection string to Azure.

  3. Produce and manually run a script.

     $ dnx ef migrations script
    

    (or)

     PM> Script-Migration
    

The arguments for these commands (and the exact commands) are not 100% set yet. There is no official documentation on migrations. In the meantime, this design document shows the planned commands for migrations.

UPDATE

The API is now

context.Database.Migrate()

Popular Answer

Below code in Startup.cs will apply database migration on startup.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        // other app setup omitted.

        if (env.IsDevelopment())
        {
            // development settings here.
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // production settings here.
            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                                             .CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<YourDbContext>()
                                .Database.Migrate();
                }
            }
            catch
            {
                // ignored
            }
        }
    }



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why