Search code examples
c#entity-framework-migrations.net-6.0asp.net-core-6.0ef-core-6.0

Why does "dotnet ef migrations add" start my application?


I've created a new project using .NET 6 and EF Core 6 but when I try to create a migration using dotnet ef migrations add, the CLI begins running the application after "Build succeeded.".

This isn't preventing the migrations from being created but adds a considerable amount of time to the process as I need to wait for the application to exit before issuing any other commands.

Snippet of dotnet ef migrations add output:

snippet of dotnet ef migrations add output

Within the same solution I have many other projects using .NET 5 and EF Core 5 which all create migrations as expected (just builds the project, doesn't run it).

Is this new functionality for EF Core 6 or is there a configuration somewhere which would cause this behaviour?

EDIT

It seems like the issue is EF Core ignoring implementations of IDesignTimeDbContext factory during migration creation and instead defaults to obtaining an instance of the DbContext from the host builder. Apparently can also happen with EF Core 5.

There is an open issue on the dotnet/efcore github here: Migrations script not using IDesignTimeDbContextFactory


Solution

  • I also met this problem. I use ASP.Net Core 6 WebApi with full controllers.

    I saw march's comment on a GitHub issue (Migrations script not using IDesignTimeDbContextFactory), which gave me inspiration.

    So, I changed WebHost.CreateDefaultBuilder(args)(obsolete in .NET6) to Host.CreateDefaultBuilder(args) in Program.cs and now the problem is solved. Unfortunately, I still don't know the specific causes of the problem.

    "dotnet ef migrations add" will still start application but Host will throw a StopTheHostException to stop the ASP.NET Core Host and then will create migration related files successfully which likes

    Build started...
    Build succeeded.
    [16:46:18 INF] Configuring web host (Identity.API)...
    [16:46:18 FTL] Program terminated unexpectedly (Identity.API)!
    Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
       at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
       at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
       at Microsoft.Extensions.Hosting.HostBuilder.Build()
       at Program.<<Main>$>g__CreateHostBuilder|0_0(IConfiguration configuration, String[] args) in G:\ASPNETCore\HongJieSun.Innermost\Services\Innermost.Identity\Innermost.Identity.API\Program.cs:line 47
       at Program.<Main>$(String[] args) in G:\ASPNETCore\HongJieSun.Innermost\Services\Innermost.Identity\Innermost.Identity.API\Program.cs:line 11
    To undo this action, use Remove-Migration.