'Can't add controller with scaffold c# .net
When I try to add new controller with scaffold visual studio prompt a error message:
There was an error running the selected code generator:
Unable to resolve service for type 1Microsoft.EntityFramework.DbContextOptions1


I have already check other question about the same problem but the answer didn't applied to my case cause already is a reference in my DbContext class to DbContext
public class HospitalDbContext : DbContext
{
public HospitalDbContext(DbContextOptions<HospitalDbContext> options)
: base(options)
{
}
public virtual DbSet<Product> Products { get; set; } = null!;
}
And Program.cs is
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddControllersWithViews();
var conf = builder.Configuration;
builder.Services.AddDbContext<HospitalDbContext>(options => options.UseSqlServer(
conf.GetConnectionString("Default")
)
);
var app = builder.Build();
This is the project link on github under branch "stackoverflow": https://github.com/heitorgiacominibrasil/Hospital-Management-System-ASPNETCORE/tree/stackoverflow
Solution 1:[1]
I have had something similar happend once. I am not sure if this will apply to this issue but when I had this error, I just kept on pressing the "Add" button. After a couple of tries it just added the controller.
Not really sure if it will fix it but everytime I do this it works.
Solution 2:[2]
Solved by creating a new asp.net core mvc project, added an folder with the models/classes I needed, added the dbcontext and generated the scaffold process again. After the scaffold finished I coppied the controllers and views to my original project. This problem seems to happens when are multiple projects, and scaffold can't handle.
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 | Kasper |
| Solution 2 | Heitor Giacomini |
