InvalidOperationException: Unable to resolve service for type 'tdbcontext' while attempting to activ

Posted by Sheonarayan under Error and Solution on 2/15/2017 | Points: 10 | Views : 13857 | Status : [Administrator] | Replies : 1

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



Responses

Posted by: Allanblackford on: 8/2/2018 [Member] Starter | Points: 25

Up
0
Down
Thanks for your reply. It saved me a lot of time. I wonder why VS doesn't fix this or do this correctly when creating models from Database first?

Sheonarayan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response