I am migrating a ASP.NET project into ASP.NET Core and I was trying to implement DbContext functionality in .NET Core. I am trying to pass different SQL Server information to the optionsBuilder that I am passing as a parameter to the base constructor. I have the following context model class:
public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext() : base (CreateOptions(null))
{}
public CompanyFormsContext(string connName) : base (CreateOptions(connName))
{}
//NEED TO CONNECT CONFIGURATION HERE
private static DbContextOptions<CompanyFormsContext> CreateOptions(string connName)
{
var optionsBuilder = new DbContextOptionsBuilder<CompanyFormsContext>();
if (connName == null)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;");
}
else
{
//THIS IS HOW IM TRYING TO MAKE IT
//similar to --> Configuration["Data:CompanyFormsContext:ConnectionString"]"
optionsBuilder.UseSqlServer(Configuration["Data:" + connName + ":ConnectionString"]);
}
return optionsBuilder.Options;
}
...
I want to pass in my SQL Server information through the information in appsettings.json which is the following:
"Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;"
}
},
I have found the following question but I believe the syntax has changed a bit since the RC2 update because I cannot use the solutions or I'm doing it wrong.
Setting the SQL connection string for ASP.NET 5 web app in Azure
How could I use a syntax similar to Configuration["Data:CompanyFormsContext:ConnectionString"] for the SQL Server input? Or is there a better way of doing this? What should be in the Startup file specifically? I have the following:
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();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddOptions();
}
...
If requested, I can simplify the question to specifically ask about using appsettings.json in the model class. I realize that I have extra information here for clarifying the specific situation.