I'm currently working on a project based on ASP.NET Core that utilizes Entity Framework Core with a data-first approach. However, when I attempt to run the 'add migration' command, I encounter the following error: 'Unable to create an object of type '(DbContext Name)'. For the different patterns supported at design time, please see https://go.microsoft.com/fwlink/?linkid=851728'.

I have also attached an image to show you the error encountered while adding a migration. I searched for the same error on Google, but after struggling for an hour, I found the solution. 

So, I decided to share my mistake and the possible reasons for that error so that it can help other developers.

The error message "Unable to create an object of type 'DbContext'" typically occurs when the application fails to create an instance of the DbContext class during design-time operations". This indicates some issue with the connection string or connectivity with the database. Here's i;m sharing some checklist that you need to go through:

1.Ensure DbContext Has a Parameterless Constructor:

Make sure your DbContext class has a parameterless constructor. If you have additional constructors, ensure that there's still a parameterless one available.

2.Check DbContext Registration:

Ensure that your DbContext is properly registered in the ConfigureServices method of the Startup class for .NET versions before 6, and in program.cs for .NET 7 or 8. This registration is necessary for dependency injection to work correctly.

In my case, I incorrectly registered the DbContext. Please make sure to register the DbContext before var app = builder.Build(); in your code. In my code, I mistakenly placed the DbContext registration code after var app = builder.Build();, which is why I'm encountering this error.

Wrong Code 

using Microsoft.EntityFrameworkCore;
using RazorDemoApplication.Database;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();



var app = builder.Build();
// Add services to the container.

builder.Services.AddDbContext<SchoolDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Myconnection")));

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
Correct Code
using Microsoft.EntityFrameworkCore;
using RazorDemoApplication.Database;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

//=>--This Line should be here above var app = builder.Build();
builder.Services.AddDbContext<SchoolDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Myconnection"))); var app = builder.Build(); // Add services to the container. // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run();

3.Check your connection string in Appsettings.json: 

Ensure that the connection defined in the Appsettings.json file is correct.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "Myconnection": "Data Source=DESKTOP-MFLCOI2;Initial Catalog=SchoolDb;User ID=sa;Password=adk@1234;Encrypt=false;"
  },
  "AllowedHosts": "*"
}

4.Make sure to set your project as the Startup Project 

  1. Make sure to set your project as the Startup Project if you have multiple projects in one solution.
  2. In the Package Manager Console, set your data access layer as the default project, which is the project that communicates with the database.
  3. After these two steps, run the command again; it should work fine.

5.Make sure the code is placed in the ConfigureServices method:

services.AddDbContext<SchoolDbContext>();