title: dotnet core: How do I get Entity Framework to read the connection string from a config file?
body: <p>I am migrating a .NET 4.x application (Class library and MS Test project, no web app) to dotnet core 2.1 and I cannot work out how to pass my SQL Database connection string to Entity Framework.</p>
  
  <p>In .NET 4.x I had app.config and this code and entity framework magically used the connection string from the app.config file. easy :)</p>
  
  <pre><code>&lt;connectionStrings&gt;
  &lt;add name="ApplicationDataConnectionString" connectionString="" providerName="System.Data.SqlClient" /&gt;
  </code></pre>
  
  <p> </p>
  
  <p>and a DBContext where pass in a Database name</p>
  
  <pre><code>public class ApplicationDataDbContext : DbContext
  {
      …
  
      public ApplicationDataDbContext(string databaseName) : base("name=ApplicationDataConnectionString")
      {
  }
  </code></pre>
  
  <p>Dotnet core has no app.config and no configuration manager. So … I can read the connection string from a config file and do something like this, but how I come from there and pass it to the DBContext, I don't know … plus this approach feels wrong also.</p>
  
  <pre><code>public class ApplicationDataDbContext : DbContext
  {
      …
  
      public ApplicationDataDbContext(string databaseName) : base("name=ApplicationDataConnectionString")
      {
  
              _config = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json")
              .Build();
  
              var myConnectionString = _config.GetConnectionString("ApplicationData");
  }
  </code></pre>
  
  <p>This is how I use the DBContext</p>
  
  <pre><code>public void SomeMethod()
      {
          using (var context = new ApplicationDataDbContext(Common.Constants.ApplicationDataDBName))
          {
            ...
          }
      }
  </code></pre>