1

I have been following the steps from https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db for creating a project and when i get to the final step for scaffolding a controller for one of my entities i get the error "no parameterless constructor defined for this object". I have looked at the link from stackoverflow for the exact same issue ASP.NET MVC: No parameterless constructor defined for this object but I have a parameterless constructor present as seen in the code below.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        var connection = "connection string here";
        services.AddDbContext<SchoolManagementContext>(options => options.UseSqlServer(connection));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }

}

}

program.cs

 var host = new WebHostBuilder()
          .UseKestrel()
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .UseStartup<Startup>()
          .UseApplicationInsights()
          .Build();
           host.Run();
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Freiza1991
  • 71
  • 1
  • 2
  • 9

1 Answers1

1

The answer to this is I updated to .Net Core 2.0 and my program.cs was still using a format that involves 1.0. I changed my code to the below and i was able to create my controllers successfully.

Changed from:

          var host = new WebHostBuilder()
              .UseKestrel()
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseIISIntegration()
              .UseStartup<Startup>()
              .UseApplicationInsights()
              .Build();
               host.Run();

TO:

    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Freiza1991
  • 71
  • 1
  • 2
  • 9