Started building up an API solution with Azure Functions with runtime version 3.x and .NET Core 3.1. In the solution using also Entity Framework Core 3.1 with code first approach.
Check the .csproj file:
<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>
In the StartUp
class I have the following to create the database context:
public RequestContext CreateDbContext(string[] args)
{
string sqlConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
var optionsBuilder = new DbContextOptionsBuilder<RequestContext>();
optionsBuilder.UseSqlServer(sqlConnectionString);
return new RequestContext(optionsBuilder.Options);
}
So in the project I have my models for migrations and running the command with .NET Core CLI as the following:
dotnet-ef migrations add InitDb
Meanwhile running the Azure Function locally there are no issues, it can read the connection string value from local.settings.json file without any issues. Once running the migrations command I get the following error:
Value cannot be null. (Parameter 'connectionString')
Question:
So it's clear it cannot find the environment variable called SqlConnectionString
once running the migrations command. Using Visual Studio 2019 with Package Manager Console there is a way to solve this issue by setting up the environment variable as the following command before running migrations:
$env:SqlConnectionString="Server=<connection-string-value>"
It's pretty annoying to switch between PMC and VS Code just because of this step if I want to run migrations. I was checking different answers in similar topics but none of them helped me that much.
So is there any way to do the same and setup environment variable with VS Code terminal using bash? Or what could be the possible solution for this scenario?
Thank you!