Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core 2.0 connection string in Azure Functions .NET Core

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?

like image 907
Boris Lipschitz Avatar asked Dec 14 '17 04:12

Boris Lipschitz


People also ask

How do I get Azure function connection string?

Get connection informationSign in to the Azure portal. Select SQL Databases from the left-hand menu, and select your database on the SQL databases page. Select Connection strings under Settings and copy the complete ADO.NET connection string.

Can I use Entity Framework with Azure functions?

NET 5 Azure Functions. Entity Framework can be used in . NET 5 Azure Functions for many different use cases, for example, using it to connect to a database like Azure SQL Database, MySQL or any other accessible and supported databases.

Do Azure functions support .NET core?

Supports all languages. Use this version to run C# functions on . NET Core 3.1 and . NET 5.0.

Can I use EF in .NET core?

Entity Framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database. EF Core is intended to be used with . NET Core applications.


1 Answers

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");
like image 135
Mikhail Shilkov Avatar answered Oct 17 '22 22:10

Mikhail Shilkov