【问题标题】:Running EF Core migrations does not find environment variable in VS Code运行 EF Core 迁移在 VS Code 中找不到环境变量
【发布时间】:2020-05-11 17:34:32
【问题描述】:

开始使用运行时版本 3.x.NET Core 3.1Azure 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 2019Package Manager Console 一起使用,可以通过在运行迁移之前将环境变量设置为以下命令来解决此问题:

$env:SqlConnectionString="Server=<connection-string-value>"

如果我想运行迁移,仅仅因为这一步就在 PMCVS Code 之间切换非常烦人。我检查了类似主题的不同答案,但没有一个对我有太大帮助。

那么有没有什么方法可以使用 bash 对 VS Code 终端执行相同的操作并设置环境变量?或者这种情况的可能解决方案是什么?

谢谢!

【问题讨论】:

标签: bash visual-studio-code entity-framework-core azure-functions


【解决方案1】:

问题是我最初试图创建一个没有export 关键字的环境变量。因此使用 bash dotnet migrations 中的以下命令导致 Value cannot be null 错误:

SqlConnectionString="Server=<connection-string-value>"

根据Jim Xu 的评论,我创建了一个似乎可以解决问题的环境变量:

export SqlConnectionString="Server=<connection-string-value>"

查看完整日志:

$ export SqlConnectionString="Server=<connection-string-value>"

$ echo $SqlConnectionString
Server=<connection-string-value>

$ dotnet-ef migrations add InitDb
Build started...
Build succeeded.

Done. To undo this action, use 'ef migrations remove'

帮助解决问题的参考文献是:

  1. Environment variable vs Shell variable, what's the difference?
  2. 您还可以在 SO 链接中找到更多信息:Defining a variable with or without export

感谢分享该链接!

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 2020-12-21
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多