Azure Functions .NET Core中的EF Core 2.0连接字符串

10

我正在使用.NET Core在Azure Functions中使用EF Core 2.0。我试图从local.settings.json文件中读取数据库连接字符串,它的定义如下:

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

Environment.GetEnvironmentVariable()方法不返回任何连接字符串的信息,同时我也无法在 .net core 中使用 ConfigurationManager.ConnectionStrings。 那么我该如何从代码中访问连接字符串?


你如何在本地加载 EFCore 2.X 配合 Azure Functions?我尝试过,但无法加载 EFCore。你是使用 Visual Studio 吗? - DOMZE
@DOMZE 是的,我使用的是VS 2017,版本15.5.2,并且采用.net core 2函数模板<PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <AzureFunctionsVersion>v2</AzureFunctionsVersion> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" /> <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.6" /> </ItemGroup> - Boris Lipschitz
@DOMZE请确保引用Sdk.Functions 1.0.6和2.0.0 EF。目前存在Azure Functions .NET Core bug。 - Boris Lipschitz
1
@DOMZE https://github.com/Azure/Azure-Functions/issues/625#issuecomment-351563570 - Boris Lipschitz
你,我的朋友,真是个救星!非常感谢你。 - DOMZE
哈哈哈哈。是啊,我也浪费了几个小时在那上面... - Boris Lipschitz
2个回答

13

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

AmbientConnectionStringProvider.Instance.GetConnectionString("MyDbConnStr")

这个类将工作委派给名为 ConfigurationUtility 的内部类,该类与某些内容相一致。

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

哇!它起作用了!谢谢!这个不在任何文档中记录。我从来没有想到过…… - Boris Lipschitz
1
这里有文档 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration 配置具有足够简单的机制,可以从环境变量、JSON或INI中加载配置。 - Smit
我该如何使用除连接字符串以外的其他配置变量?它无法与自定义参数一起正常工作。 - Jonathan

9
您可以使用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); 来获取值。


1
这在本地开发时可以工作,但是如何在Azure门户中设置此值? - Métoule

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接