新的.Net Core 2站点不会重新配置Configuration.GetConnectionString

Mat*_*ete 9 c# entity-framework-core asp.net-core asp.net-core-2.0 asp.net-core-3.0

我正在从一个空的ASP.NET Core 2模板创建一个新的网站,并按照Microsoft Entity Framework Tutorial帮助我进行设置.有一点,你有添加代码:

services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

gld*_*ael 22

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

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

public IConfiguration Configuration { get; }
Run Code Online (Sandbox Code Playgroud)

我很惊讶你怎么没有它,因为它是模板的一部分.

  • 谢谢,我敢打赌这是普通 MVC 模板的一部分,但该模板添加了我不想要的其他东西,所以我使用了空模板,我必须在其中添加 servives.AddMVC() 我自己,所以这是我做的可能性需要添加。我将在明天午休时间再次进行这个项目时进行测试。 (2认同)