0

I just upgraded from 1.1 to 2.1 and when I run: dotnet ef migrations add spottedmahn, I get:

Unable to create an object of type 'MyDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

spottedmahn
  • 14,823
  • 13
  • 108
  • 178

1 Answers1

3

You need to define IWebHost BuildWebHost(string[] args) or IWebHostBuilder CreateWebHostBuilder(string[] args) in Program.

The method name matters (I had CreateWebHost and it was failing).

For me, "Add an implementation of 'IDesignTimeDbContextFactory' to the project" was a red herring. It couldn't find my IWebHostBuilder so it couldn't use the ServiceProvider configured for my DbContext. Using the accepted answer here might be valid for some people but violates DRY for me.


Using this answer I ran my migration in verbose mode: dotnet ef migrations add spottedmahn -v:

Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding IWebHost accessor...
No CreateWebHostBuilder(string[]) method was found on type 'MyApp.Web.Program'. No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'MyDBContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'MyDBContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> System.MissingMethodException: No parameterless constructor defined for this object.

I then noticed "No CreateWebHostBuilder found...". After some experimentation I learned either of these code segments are valid.

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

or

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

The doc page only refers to the BuildWebHost method but the verbose log refers it refers to the CreateWebHostBuilder method. ‍♂️

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
  • Same thing for Entity Framework Core 3.0.0 - the EF.Tools seem to create their runtime-context using a method named BuildWebHost() in the executing assembly. – Sascha Oct 02 '19 at 14:29