why remove-migration run my app?

Update for ASP.NET Core 2.1

In ASP.NET Core 2.1 the methods changed slightly. The general method is similar to the 2.0, just the methods name and return types have been changed.

public static void Main(string[] args)
{
    CreateWebHostBuilder(args)
        .Build()
        .Migrate();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    return new WebHostBuilder()
        ...; // Do not call .Build() here
}

ASP.NET Core 2.0

If you are on ASP.NET Core 2.0/EF Core 2.0 then there’s been a change to better cover such cases, so that the command line tools can work better.

It’s pretty well covered in this announcement.

It boils down to having a static BuildWebHost method which configures the whole application, but doesn’t run it.

  public class Program
  {
      public static void Main(string[] args)
      {
          var host = BuildWebHost(args);

          host.Run();
      }

      // Tools will use this to get application services
      public static IWebHost BuildWebHost(string[] args) =>
          new WebHostBuilder()
              .UseKestrel()
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseIISIntegration()
              .UseStartup<Startup>()
              .Build();
  }

Also with EF 2.0 it’s now recommended to move the migrations to the main method after BuildWebHost has been called. For example

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args)
            .Migrate();

        host.Run();
    }

Where Migrate is an extension method:

public static IWebHost Migrate(this IWebHost webhost)
{
    using (var scope = webhost.Services.GetService<IServiceScopeFactory>().CreateScope())
    {
        using (var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>()) 
        {
            dbContext.Database.Migrate();
        }
    }
    return webhost;
}

Now migrations only run, when your application is executed. When you run command line tools, only BuildWebHost will be called and no migrations applied.

Leave a Comment