Site icon Ryadel

BuildWebHost - Unable to create an object of type ApplicationDbContext error in EF Core 2.x - How to Fix

BuildWebHost - Unable to create an object of type ApplicationDbContext error in EF Core 2.x - How to Fix

A couple days ago I had to fix a EF Core issue experienced to one of my readers when he was working on the EF Core Migrations (Chapter 4 of ASP.NET Core 2 and Angular 5 book). This was the error, as reported on GitHub:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider.
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to
the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

The issue

After some research through the official docs and similar issues I've seen that it was mostly due to the fact that they changed the behaviour of how the BuildWebHost method - which is invoked in the Program.cs  file to obtain the application services - works: now it invokes the Configure method in the Startup.cs  file, which could lead to unexpected problems if that method contains some database initialization code. The major issue there is that such "problems" will most likely raise misleading exceptions whenever the seeding code runs before the first dotnet ef migrations add  / dotnet ef database update  command execution - when the database doesn't yet exist.

The fix

Luckily enough, fixing that is just as easy as following the official EF Core 1.x to 2.x migration guide:

  • Remove all the DB initialization code from the Startup.cs file's Configure()  method.
  • Put it into the Program.cs file's Main()  method, in the following way:

That's about it!

If you want to know more about .NET Core and Angular check out the ASP.NET Core 2 and Angular 5 book, available in paperback and/or digital format. Promo Code: ASPCA50 to get it with a 50% discount! The book's latest edition, updated to ASP.NET Core 5 and Angular 11, is available here.

 

 

Exit mobile version