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:
Make sure your DbContext class has a parameterless constructor. If you have additional constructors, ensure that there's still a parameterless one available.
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();
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": "*"
}
services.AddDbContext<SchoolDbContext>();