尝试在 .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>();
}
我尝试创建一个控制器.我选择添加的控制器类型是MVC Controller with views, using Entity Framework".尝试创建时,在窗口中我指定了模型类,并勾选了生成视图"、参考脚本库"和使用布局页面",顺便说一下,默认情况下是勾选的.指定布局页面的文本框留空.
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 类和一个里面的配置属性
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 也在启动类 ConfigureServices() 方法中注册.
You would have to make sure that the DbContext is registered in the Startup class ConfigureServices() method as well.
Startup Class中的第一次注入IConfiguration接口:
First Injection IConfiguration interface in Startup Class:
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屋!