EFCore: Setting ConnectionString at runtime
Posted: Mon 12 Nov 2018 08:30
Hello,
using the Entity Developer I created a simple Model based on an existing database. Within a .Net Core ApiService I try to access the model an get an error:
The appsettings.json file contais the connectionstring:
When setting a breakpoint in Startup.cs I can read the data from appsettings.json: (e.g. in Immediate Window)
But when the model is accessed in code I get an error:
So, what do I have to do to get this running? Change the auto-generated code? Or use a different file then appsettings.json? (I tried by adding web.config. but same error).
Just to make sure that there's no error in the model I created a .NET Framework Project that uses the model from above. When I added the connectionstring in app.config it all workes fine.
using the Entity Developer I created a simple Model based on an existing database. Within a .Net Core ApiService I try to access the model an get an error:
The appsettings.json file contais the connectionstring:
Code: Select all
"ConnectionStrings": {
"FOOModelConnectionString": "User Id=FOOUSER;Password=FOOPASS;Server=FOOSRV;Direct=True;Sid=FOOSRV;Persist Security Info=True;License Key=AQuiteLongString"
}
Code: Select all
?Configuration.GetConnectionString("FOOModelConnectionString")
Taking a look at the auto-generated (by Entity Developer) FOO.FOOModel.cs I find teh folling Code:Connection string "FOOModelConnectionString" could not be found in the configuration file.
Code: Select all
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
if (!optionsBuilder.Options.Extensions.OfType<RelationalOptionsExtension>().Any(ext => !string.IsNullOrEmpty(ext.ConnectionString) || ext.Connection != null))
optionsBuilder.UseOracle(GetConnectionString("FOOModelConnectionString"));
}
CustomizeConfiguration(ref optionsBuilder);
base.OnConfiguring(optionsBuilder);
}
private static string GetConnectionString(string connectionStringName)
{
System.Configuration.ConnectionStringSettings connectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringSettings == null)
throw new InvalidOperationException("Connection string \"" + connectionStringName +"\" could not be found in the configuration file.");
return connectionStringSettings.ConnectionString;
}
Just to make sure that there's no error in the model I created a .NET Framework Project that uses the model from above. When I added the connectionstring in app.config it all workes fine.