温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - New .Net Core 2 Site does not reconize Configuration.GetConnectionString
asp.net-core asp.net-core-2.0 asp.net-core-3.0 c# entity-framework-core

c# - 新的.Net Core 2站点不符合Configuration.GetConnectionString

发布于 2020-04-07 10:36:25

我正在从一个空的ASP.NET Core 2模板创建一个新网站,并按照Microsoft Entity Framework教程来帮助我进行设置。一方面,您可以添加代码:

services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

要的ConfigureServices()方法Startup.cs我这样做了,但是在我的项目Visual Studio中,我ConfigurationConfiguraiton.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();
}

查看更多

提问者
Matthew Verstraete
被浏览
87
gldraphael 2017-12-08 03:51

您需要IConfiguration通过DI 获取对象。在您的的构造函数中
添加一个IConfiguration参数Startup,并将其分配给一个Configuration属性:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

我很惊讶您却没有它,因为它是模板的一部分。