'Add-Migration command has an error in my .NET 6 project

I have a project and created it using .NET 6.

I used the Add-Migration command before adding some DbSet in my DbContext, it worked correctly and made migration files for me.

Today add a new DbSet to my DbContext after that used the Add-Migration command but I get an error:

Unable to create an object of type 'HospitalNetDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I get some information from this link but I can't solve my problem.

Some people suggested using contractor without parameter in DbContext class, but when I add this contractor to DbContext class and after that, I used the Add-Migration command, I get a new error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

After this error I added a new constructor same as below but my problem still persists:

public HospitalNetDbContext(DbContextOptions<HospitalNetDbContext> options) : base(options)
{
}

More information about my project is connection string defined into the app settings file and in startup file using below code for set connection string to DbContext instead of add into overriding OnConfiguring method in the DbContext class.

services.AddDbContext<HospitalNetDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("HospitalNetDb")));


Solution 1:[1]

I had the same error and the issue for me was that I hadn't specified the startup project and target project.

The class I was using that inherited from DbContext was in a data access project separate from the startup project, and I think it meant that without specifying the startup project the configuration in program.cs hadn't run when it was trying to initialise the context class and that's why it failed. When I ran it like this it worked:

Add-Migration -Name MyNewMigration -StartupProject {startup project name} -Project {project containing HospitalNetDbContext}

This page was helpful for me https://docs.microsoft.com/en-us/ef/core/cli/powershell#target-and-startup-project.

Solution 2:[2]

In my projects I have 2 constructors in DbContext, one empty and one with DbContextOptions. Also checkout to override the OnConfiguring method in your DbContext.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 panamana
Solution 2 Jelle Schräder