I am creating a new web site from an empty ASP.NET Core 2 template and following the Microsoft Entity Framework Tutorial to help me get setup. At one point it has you add the code:
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
To the ConfigureServices()
method of Startup.cs
. I did this but in my project Visual Studio give me that little red line under Configuration
in the Configuraiton.GetConnectionString
I had thought I was missing a using
statement or even a package but the Visual Studio 2017 quick actions don't identify a using
statement to use and I do have the Microsoft.AspNetCore.All
package installed so I should have all the packages.
What am I missing that is making the Configuration
not recognized?
Edit: The error is:
The name 'Configuration' does not exist in the current context
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CollectionContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
You need to get the IConfiguration
object via DI.
Add a IConfiguration
argument to your Startup
's constructor, and assign it to a Configuration
property:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
I'm surprised how you don't have it though, because it's part of the template.
Thanks, I would bet that is part of the normal MVC template but that template adds other things I did not want so I went with the empty template where I had to add the servives.AddMVC() my self so this is probability something I do need to add. I will test on lunch break tomorrow when I work on this project again.
This worked, I checked the normal MVC project template and it is part of that template but it is not part of an empty template.
Also seems to be missing in Web API project, even though Web API is delivered via MVC in asp.net core 2, as I understand it. Looks like
using Microsoft.Extensions.Configuration;
is what I want...@Andrew I have the feeling you're doing something wrong... You shouldn't need to inject IConfiguration into your DbContext... feel free to open a new question and someone will help you.
This tutorial never works out of box. Now, for 3.0.0 preview (at least for VS for mac: docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/… ) the
Startup.cs
is missing declaration for Configuration, e.g. something likeprivate IConfiguration Configuration;
( FYI: The lines 11 - 28 of Startup.cs: i.stack.imgur.com/cL8X8.png ) ... also theAdd NuGet packages and EF tools
section on the tutorial page follows their use in theAdd a database context class
section ... no/poor QA/QC on these tutorials...