After scaffolding models from existing database in ASP.NET Core, I was getting following error when accessing my controller action method.
InvalidOperationException: Unable to resolve service for type 'ASPNETCoreTutorials.Models.TrainingDatabaseContext' while attempting to activate 'ASPNETCoreTutorials.Controllers.CategoriesController'.
The solution of this error is in two steps
1. Go to your database context (in this case TrainingDatabaseContext) and
remove the OnConfiguring method that looks like this.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
2. Go to Startup.cs file and add .AddDbContext method like this (this actually adds the framework service to the project so that your database context is accessible.
public void ConfigureServices(IServiceCollection services)
{
//.....
services.AddDbContext<TrainingDatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Build the project and you are good to go.
Regards,
Sheo Narayan
http://www.dotnetfunda.com