Azure Functions .NET Core 中的 EF Core 2.0 连接字符串
Posted
技术标签:
【中文标题】Azure Functions .NET Core 中的 EF Core 2.0 连接字符串【英文标题】:EF Core 2.0 connection string in Azure Functions .NET Core 【发布时间】: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 模板您可以使用Microsoft.Azure.WebJobs.Host
中的帮助类之一:
AmbientConnectionStringProvider.Instance.GetConnectionString("MyDbConnStr")
这个类将工作委派给名为ConfigurationUtility
的内部类,它的工作符合
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", true)
.Build();
var conn = configuration.GetConnectionString("MyDbConnStr");
【讨论】:
哇!有用!谢谢!它没有记录在任何地方。我永远不会猜到... 这里记录了 docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/… 配置具有足够简单的机制来从 env/json/ini 加载配置。 如何使用任何其他配置变量,而不是连接字符串。它不适用于自定义参数【参考方案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 门户中设置此值?以上是关于Azure Functions .NET Core 中的 EF Core 2.0 连接字符串的主要内容,如果未能解决你的问题,请参考以下文章