16

Currently in Startup, I have my sql server string looking like this:

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=servername;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true";
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection));
}

How do I use what's in my appsettings.json:

{
  "Data": {
    "DefaultConnection": {
    "ConnectionString": "Data Source=server;Initial Catalog=database;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

To look something like this in the new ASP.NET 1.0 CORE new setup to look paramertized like this:

public void ConfigureServices(IServiceCollection services)
{
    var connection2 = new SqlConnection connectionString;
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection2));
}

Also, if I have a different database for the test and qa, how do I let the ASP.NET app know to use a connection for each environment?

My startup class is already defined at the root like this:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
0

2 Answers 2

17

Use proper structure for connection strings:

{
  "ConnectionStrings": {
    "DefaultConnection": "xxx"
  }
}

Access in startup.cs:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Sign up to request clarification or add additional context in comments.

2 Comments

I get: Error: The name "Configuration" does not exist in the current context. Which package am i missing? EDIT: Never mind, this is an issue in the pre-release of v2. In 1.1 stable version it's ok.
you are missing the IConfiguartionRoot method in the Startup.cs file. Name it configuaration, add a get to it, and you're done.
0

First add package for SQL server "Microsoft.EntityFrameworkCore.SqlServer" then add

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

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.