why remove-migration run my app?

asp.net-core ef-migrations entity-framework-core

Question

I did some version upgrade in last months and now I noticed that when I use "remove-migration" to delete migration that I reverted, it's first run my app.

(I noticed that because we do update-database inside startup, so I got to situation where I can't remove migrations, since every time I tried remove migration - it automatically ran the startup which apply the migration to db, then it failed delete it, since it see it in db.)

any idea?

1
10
8/29/2017 2:27:26 PM

Accepted Answer

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.

25
9/25/2018 3:42:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow