2

I have created an ASP.NET Core web application. I am trying to add Entity Framework Core to my solution.

I have installed the below nugets to the project.

  • "Microsoft.NETCore.App",
  • "Microsoft.AspNetCore.App"
  • "Microsoft.EntityFrameworkCore.SqlServer"

There is a DbSet defined in the Context.

In the startup class when i try to add the Db Context, I get the following error in the for "Configuration".

The Name Configuration does not exist in the current context.

My code is:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

I am following this article which doesn't say much about the configuration

4
  • Did you include the relevant IConfiguration Configuration property/field in the startup? Commented Jan 27, 2020 at 11:28
  • I suggest to you this link for resolve problem :stackoverflow.com/a/59653471/5576498 Commented Jan 27, 2020 at 11:40
  • @AminGolmahalle thank you for the reply. I am a newbie to .Net Core. I dont have a appSettings.json in the solution. There is a launchSetting.json under Properties. How should a add the ConnectionString? Should I create a new .json file in the solution for this? Please advise Commented Jan 27, 2020 at 12:38
  • 1
    @sm101 For learning about concpet asp.net core please see this link: stackoverflow.com/a/59701684/5576498 Commented Jan 27, 2020 at 13:06

1 Answer 1

5

The code sample is incomplete. The Configuration actually is a property of the Startup class. It is populated via constructor dependency injection.

public class Startup
{
    public IConfiguration Configuration { get; }

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }

    //...
}

As mentioned on the last step of the article : the full code is available on https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/data/ef-mvc/intro/samples/cu-final

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.