c# - Azure Functions 环境变量始终为 null

标签 c# azure .net-core entity-framework-core azure-functions

在我的 V3 函数项目中,我尝试连接 Entity Framework 并从环境变量传递连接字符串。

在我的 local.settings.json 文件中,我有:

{
  "Values" : {
    "SqlConnectionString" : "<localdb connection string here>"
  }
}

我正在按照this blog post使用IDesignTimeContextFactory连接上下文。 :

public class ContextFactory : IDesignTimeDbContextFactory<Context>
    {
        public Context CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<Context>();
            var connectionString = Environment.GetEnvironmentVariable("SqlConnectionString", EnvironmentVariableTarget.Process);
            optionsBuilder.UseSqlServer(connectionString);

            return new Context(optionsBuilder.Options);
        }
    }

当我尝试添加迁移时,connectionString 为空。

谁能看出这里出了什么问题吗?

编辑:

按照建议,我还尝试定义连接字符串并注入(inject) IConfiguration,如下所示:

    public class ContextFactory : IDesignTimeDbContextFactory<Context>
    {
        private readonly IConfiguration _configuration;

        public ContextFactory(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public Context CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<Context>();
            optionsBuilder.UseSqlServer(_configuration.GetConnectionString("SqlConnectionString"));

            return new Context(optionsBuilder.Options);
        }
    }

但我得到以下异常:

System.MissingMethodException: No parameterless constructor defined for type 'EbayTools.Functions.Domain.ContextFactory'.

最佳答案

说明

我在遵循同一篇博客文章/教程时遇到了同样的问题!

运行 Entity Framework Core CLI 工具时,local.settings.json 中的值不会添加到环境变量列表中。您可以通过提示调试器运行来检查这一点(参见代码)。

为了在运行 Entity Framework Core CLI 命令时访问 local.settings.json 中的值,我使用了 ConfigurationBuilder(再次参见下文)。

最后,我将连接字符串存储在 local.settings.json 文件的“Values”下,而不是 ConnectionStrings 下。


解决方案

ProjectContextFactory.cs

public class ProjectContextFactory : IDesignTimeDbContextFactory<ProjectDbContext>
{
    public ProjectDbContext CreateDbContext(string[] args)
    {
        // Prompt debugger to open when running ef cli command.
        // Remove this when you no longer need to debug
        Debugger.Launch();

        // See that environment variables list doesn't contain your key value and therefore connectionString variable returns null
        var variables = Environment.GetEnvironmentVariables();
        var connectionString = Environment.GetEnvironmentVariable("SQLDB_CONNECTIONSTRING");

        // Setup config
        var config = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        // Get connection string from config
        var connectionString = config.GetValue<string>("Values:SQLDB_CONNECTIONSTRING");

        var optionsBuilder = new DbContextOptionsBuilder<ProjectDbContext>();
        optionsBuilder.UseSqlServer(connectionString);

        return new ProjectDbContext(optionsBuilder.Options);
    }
}

本地.settings.json

{
   "IsEncrypted": false,
   "Values": { 
       "AzureWebJobsStorage": "UseDevelopmentStorage=true",
       "SQLDB_CONNECTIONSTRING": "<connectionString>
   }
}

关于c# - Azure Functions 环境变量始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62356340/

相关文章:

c# - 为什么不能推断出这些类型参数?

c# - 在 C# 中使用图像路径从 Oracle 数据库中检索图像

c# - HttpWebRequest 未传递凭据

python - 有没有办法根据时间戳列出 AzureBlobStorage 中的 blob?

azure - 在 .NET Core 控制台应用程序中以编程方式创建 New-AzureRmRoleAssignment

c# - 解除分配对象后,.NET Core 应用进程内存不会减少

c# - Prism MVVM : 'No parameterless constructor defined for type' Error when binding ViewModel to View

c# - DateTime.ParseExact() 不理解 24 小时时间值吗?

Azure Web 应用程序与 Azure 移动应用程序

asp.net - 基于 GIT 的 asp.net Web 应用程序无法部署到 Azure,并出现 typescript 编译错误