【发布时间】:2020-05-11 17:34:32
【问题描述】:
开始使用运行时版本 3.x 和 .NET Core 3.1 的 Azure Functions 构建 API 解决方案。在使用代码优先方法的Entity Framework Core 3.1的解决方案中。
检查 .csproj 文件:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<RootNamespace>project_name</RootNamespace>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />
</ItemGroup>
在StartUp 类中,我有以下内容来创建数据库上下文:
public RequestContext CreateDbContext(string[] args)
{
string sqlConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
var optionsBuilder = new DbContextOptionsBuilder<RequestContext>();
optionsBuilder.UseSqlServer(sqlConnectionString);
return new RequestContext(optionsBuilder.Options);
}
所以在项目中,我有用于迁移的模型并使用 .NET Core CLI 运行命令,如下所示:
dotnet-ef migrations add InitDb
同时在本地运行Azure Function没有问题,它可以从local.settings.json文件中读取连接字符串值没有任何问题。运行迁移命令后,我收到以下错误:
值不能为空。 (参数'connectionString')
问题:
所以很明显一旦运行迁移命令,它就找不到名为SqlConnectionString 的环境变量。将 Visual Studio 2019 与 Package Manager Console 一起使用,可以通过在运行迁移之前将环境变量设置为以下命令来解决此问题:
$env:SqlConnectionString="Server=<connection-string-value>"
如果我想运行迁移,仅仅因为这一步就在 PMC 和 VS Code 之间切换非常烦人。我检查了类似主题的不同答案,但没有一个对我有太大帮助。
那么有没有什么方法可以使用 bash 对 VS Code 终端执行相同的操作并设置环境变量?或者这种情况的可能解决方案是什么?
谢谢!
【问题讨论】:
-
@JimXu 谢谢,这有助于我了解导致我的问题的原因。
标签: bash visual-studio-code entity-framework-core azure-functions