Unable to create an object of type 'MyDbContext'. Add an implementation of 'IDesignTimeDbContextFactory'

entity-framework-core

Question

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.

1
0
9/3/2019 4:55:01 PM

Accepted Answer

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. 🤷‍♂️

1
9/3/2019 4:55:01 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