我正在从一个空的ASP.NET Core 2模板创建一个新网站,并按照Microsoft Entity Framework教程来帮助我进行设置。一方面,您可以添加代码:
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
要的ConfigureServices()
方法Startup.cs
。我这样做了,但是在我的项目Visual Studio中,我Configuration
在Configuraiton.GetConnectionString
我以为我缺少using
语句甚至程序包,但是Visual Studio 2017快速操作无法识别using
要使用的语句,并且确实安装了Microsoft.AspNetCore.All
程序包,因此我应该拥有所有程序包。
我想念的是什么使Configuration
未被认可?
编辑:错误是:
名称“配置”在当前上下文中不存在
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CollectionContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
您需要IConfiguration
通过DI 获取对象。在您的的构造函数中
添加一个IConfiguration
参数Startup
,并将其分配给一个Configuration
属性:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
我很惊讶您却没有它,因为它是模板的一部分。
谢谢,我敢打赌这是普通MVC模板的一部分,但是该模板添加了我不想要的其他东西,所以我选择了必须添加servives.AddMVC()的空模板,这是我做的可能性需要添加。明天再次进行此项目时,我将在午休时间进行测试。
这项工作有效,我检查了普通的MVC项目模板,它是该模板的一部分,但不是空模板的一部分。
据我了解,即使Web API是通过MVC在asp.net core 2中提供的,Web API项目中似乎也缺少该API。看起来
using Microsoft.Extensions.Configuration;
就是我想要的...@Andrew我觉得您做错了什么...您不需要将IConfiguration注入到DbContext中...随时打开一个新问题,有人会帮助您。
本教程永远不会开箱即用。现在,对于3.0.0预览版(至少对于Mac的VS:docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/…),
Startup.cs
缺少配置声明,例如private IConfiguration Configuration;
(FYI: Startup.cs的第11至28行:i.stack.imgur.com/cL8X8.png)...Add NuGet packages and EF tools
教程页面上的部分也遵循它们在以下Add a database context class
部分中的使用:这些教程中的否/不良QA / QC ...