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 : 554 | Status : [Administrator] | Replies : 0

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

(No response found.)

Login to post response