尝试在.NET CORE Web应用程序中创建控制器时出错 [英] Error when trying to create a Controller in .NET CORE Web Application
问题描述
我在Visual Studio 2017中创建了一个.NET CORE Web应用程序.它是作为一个空模板创建的.
I have a .NET CORE Web application created in Visual Studio 2017. It was created as a empty template.
startup.cs具有以下代码
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();
}
program.cs如下:
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>();
}
我试图创建一个控制器.我选择添加的控制器的类型为使用Entity Framework的具有视图的MVC控制器".尝试创建时,我在窗口中指定了模型类,并在生成视图",参考脚本库"和使用布局页面"中打了勾,默认情况下已打勾.用于指定布局"页面的文本框保留为空白.
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:
运行所选代码生成器时发生错误:脚手架无法编辑Startup类以使用注册新的Context依赖注入.确保有一个Startup类和一个其中的配置属性
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
无法弄清楚为什么会发生此错误.是因为DI还是实体上下文问题?
Couldn't figure out why this error is happening. Is it because of DI or Entity Context issue ?
推荐答案
您还必须确保DbContext也已在Startup类 ConfigureServices()方法中注册.
You would have to make sure that the DbContext is registered in the Startup class ConfigureServices() method as well.
首次注入 IConfiguration 接口:
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
然后将以下代码添加到ConfigureServices方法:
then Add Below Code To ConfigureServices Method:
services.AddDbContext<AppContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
,然后在 appsettings.json 中添加ConnectionString地址:
and then Add ConnectionString Address in appsettings.json :
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
这篇关于尝试在.NET CORE Web应用程序中创建控制器时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!