2017-09-02 19 views
1

我一直在關注從https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db的步驟創建一個項目,當我到達最後一步腳手架控制器爲我的實體之一,我得到的錯誤定義MVC無參數的構造函數「無參數的構造函數的定義這個對象「。我已經查看了完全相同的問題,從stackoverflow的鏈接ASP.NET MVC: No parameterless constructor defined for this object,但我有一個無參數的構造函數存在,如下面的代碼所示。此對象

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(); 

回答

1

這個問題的答案是我更新到.NET 2.0的核心和我Program.cs中仍在使用涉及的格式1.0。我將我的代碼更改爲下面,我能夠成功創建我的控制器。

變更情況:從

  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();