EF Core 2.0 connection string in Azure Functions .NET Core

azure azure-functions c# ef-core-2.0 entity-framework-core

Question

I'm using EF core 2.0 in Azure Functions using .net core. I'm trying to read db ConnectionString from local.settings.json, which is defined:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "ConnectionStrings": {
    "MyDbConnStr": "Data Source=.;Initial Catalog=xxxxxxx"
  }
}

Environment.GetEnvironmentVariable() doesn't return any connection string info neither I can use ConfigurationManager.ConnectionStrings with .net core. How do I access the connection string from the code?

1
10
12/14/2017 5:15:23 AM

Accepted Answer

You could use one of the helper classes in Microsoft.Azure.WebJobs.Host:

AmbientConnectionStringProvider.Instance.GetConnectionString("MyDbConnStr")

This class is delegating the work to internal class called ConfigurationUtility, which does something in line with

var configuration = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddJsonFile("appsettings.json", true)
    .Build();
var conn = configuration.GetConnectionString("MyDbConnStr");
13
12/14/2017 8:40:51 AM

Popular Answer

You can use Environment.GetEnvironmentVariable. The keys are "ConnectionStrings:YourKey"

Assuming your local.settings.json looks like the following:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "ConnectionStrings": {
    "sqldb_connection": "connection_string_here"
  }
}

Use Environment.GetEnvironmentVariable("ConnectionStrings:sqldb_connection", EnvironmentVariableTarget.Process); to get the value



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow