【问题标题】:EF Core 2.0 connection string in Azure Functions .NET CoreAzure Functions .NET Core 中的 EF Core 2.0 连接字符串
【发布时间】:2018-05-28 02:42:14
【问题描述】:

我在使用 .net 核心的 Azure Functions 中使用 EF 核心 2.0。我正在尝试从定义的 local.settings.json 读取 db ConnectionString:

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

Environment.GetEnvironmentVariable() 不返回任何连接字符串信息,我也不能将 ConfigurationManager.ConnectionStrings 与 .net 核心一起使用。 如何从代码中访问连接字符串?

【问题讨论】:

  • 如何在本地加载带有 azure 函数的 EFCore 2.X?我试过了,它无法加载 EFCore。你在用视觉工作室吗?
  • @DOMZE 是的,使用 VS 2017,版本 15.5.2 和 .net core 2 Functions 模板 netstandard2.0v2 PropertyGroup>
  • @DOMZE 确保您引用了 Sdk.Functions 1.0.6 和 2.0.0 EF。当前存在 Azure Functions .NET Core 错误
  • 你我的朋友是救世主!非常感谢。

标签: c# azure entity-framework-core azure-functions ef-core-2.0


【解决方案1】:

您可以使用Microsoft.Azure.WebJobs.Host 中的帮助类之一:

AmbientConnectionStringProvider.Instance.GetConnectionString("MyDbConnStr")

这个类将工作委派给名为ConfigurationUtility的内部类,它的工作符合

var configuration = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddJsonFile("appsettings.json", true)
    .Build();
var conn = configuration.GetConnectionString("MyDbConnStr");

【讨论】:

【解决方案2】:

您可以使用Environment.GetEnvironmentVariable。键是“ConnectionStrings:YourKey”

假设您的 local.settings.json 如下所示:

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

使用Environment.GetEnvironmentVariable("ConnectionStrings:sqldb_connection", EnvironmentVariableTarget.Process); 获取价值

【讨论】:

  • 这在本地开发期间有效,但是如何在 Azure 门户中设置此值?
猜你喜欢
  • 2019-03-10
  • 2020-04-14
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
相关资源
最近更新 更多