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

Problem

You may get the following error when you run the add-migration command in EF Core 5. 

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

 

Solutions

The above error can be thrown due to various reasons. The following are some of them.

solution 1

Go to your startup.cs class and check if you have registered your DbContext class for dependency injection. If not, add the code similar to the following in the ConfigureServices method of your startup.cs class. Here, my DbContext class is AddDbContext.

 public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddDbContext<AppDbContext>(options =>
              options.UseSqlServer(
                  Configuration.GetConnectionString("DefaultConnection")));
        }

My Connection string is defined in appsettings.json as follows. 

{
    "Connectionstrings": {
      "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDB;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "AllowedHosts": "*"
  }

Solution 2

Check your appsettings.json file. I got the following error when I missed a comma after the connection string

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without 
the application service provider. Error: Could not parse the JSON file.
Unable to create an object of type 'AppDbContext'. For the different patterns supported at
design time, see https://go.microsoft.com/fwlink/?linkid=851728
  {
    "Connectionstrings": {
      "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DBQuery;Trusted_Connection=True;MultipleActiveResultSets=true"
    }<-missed comma here
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "AllowedHosts": "*"
  }

 


Search