简体   繁体   中英

Error when trying to create a Controller in .NET CORE Web Application

I have a .NET CORE Web application created in Visual Studio 2017. It was created as a empty template.

The startup.cs has the below code

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton<IInventoryServices, InventoryServices>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvcWithDefaultRoute();
    }

The program.cs is like below:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}

I tried to create a Controller. The type of the controller I selected to add was "MVC Controller with views, using Entity Framework". When trying to create, in the window i have specified the model class, and ticked for "Generate views", "Reference script libraries" and "Use layout page" which by the way are ticked by default. The text-box to specify the Layout page is left blank.

When trying to create the controller I get the below error:

There was an error running the selected code generator: Scaffolding failed to edit Startup class to register the new Context using Dependency injection. Make sure there is a Startup class and a Configuration property in it

Couldn't figure out why this error is happening. Is it because of DI or Entity Context issue ?

You would have to make sure that the DbContext is registered in the Startup class ConfigureServices() method as well.

First Injection IConfiguration interface in Startup Class:

public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

then Add Below Code To ConfigureServices Method:

services.AddDbContext<AppContext>(options => 
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and then Add ConnectionString Address in appsettings.json :

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
  } 
}

You must first configure the dependency injection of the DbContext. This tutorial explain step by step what you need to do.

ASP.NET With Entity Framework

Try Updating the packages in the projects using nuget package manager to the latest.

This solved the problem "I am using .Net 5.0" so this might work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM