0

In my ASP.Net core application, Startup class has many things that is not needed to do migrations. According to This it seems I can create a DesignTimeFactory which will prepare the specified context and use it for migration purposes.

So I have created the simple class implementing IDesignTimeDbContextFactory which will simply accept a parameter, do some work with it and then return the MigrationContext for rest of the work within CreateDbContext(string[] args).

My problem is when I run Add-Migration commands from the console, it still executes StartUp class. . I thought with DesignTimeFactory, it shouldn't try to wire-up everything but simply use the context returned by the factory and use it for migration purposes.

Is there a way to avoid executing Startup class

       public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                Debugger.Launch();
                webBuilder.UseStartup<Startup>();
            });

and simply rely only on the DBContextFactory for migration? So Startup class is only executing at run time

user2058413
  • 691
  • 3
  • 10
  • 28
  • Probably something is wrong with your class implementing `IDesignTimeDbContextFactory` which prevents EF Core finding/using it. Run `Add-Migration` with `-Verbose` option and see/post the output. – Ivan Stoev Jan 02 '21 at 13:13

2 Answers2

0

Actually this has been in discussion at various levels. See this thread

So basically I renamed the CreateHostBuilder(string[] args) method name to PrepareHostBuilder(string[] args) and DesignTimeFactory stopped trying to wireup Startup stuff.

In the above URL, there is a detailed discussion going on about this.

user2058413
  • 691
  • 3
  • 10
  • 28
0

Since the EF cli supports command line arguments, a hack-ish work around is to pass in an arg of some kind to the Add-Migration or Update-Database command and check for its existence in the CreateHostBuilder(string[] args) method:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
    {
        if (!args.Contains("design"))
            webBuilder.UseStartup<Startup>();
    });

And then you could call the following command in PackageManagerConsole to skip the Startup file:

PM> Update-Database -Context MyContext -Args "design"
Ryan Naccarato
  • 674
  • 8
  • 12