我一直在遵循https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db的步骤来创建一个项目,当我完成脚手架的最后一步时--一个实体的控制器--我会得到一个错误:“没有为这个对象定义的无参数构造函数”。我已经查看过来自堆栈溢出的链接,与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();发布于 2017-09-03 01:22:37
答案是我更新到.Net Core2.0,而我的program.cs仍然使用一种包含1.0的格式。我将代码更改为下面的代码,并且能够成功地创建控制器。
改为:
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();至:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();https://stackoverflow.com/questions/46017996
复制相似问题