实体框架核心连接字符串 - 环境变量

asp.net asp.net-core c# entity-framework entity-framework-core

我有一个使用实体框架核心的.net核心应用程序。通过命令行运行实体框架迁移或更新时,我得到“值不能为null。参数名称:connectionString”

连接字符串保留为环境变量:

ConnectionStrings__SomeContextConnection  ...(localdb)\\MSSQLLocalDB...

但是,当我将完全相同的连接字符串移动到.json配置文件中时:

"ConnectionStrings": {  
    "SomeContextConnection": "...(localdb)\\MSSQLLocalDB..." 
}

然后,实体框架工具可以无问题地识别连接字符串。在调试代码时,在Startup.cs中:

var connectionString = _config.GetConnectionString("SomeContextConnection");

当字符串存储在两个位置中的任何一个位置时,connectionString变量设置为正确的字符串,但在使用环境var时尝试连接到数据库时崩溃。

(注意:在环境变量的情况下,连接字符串是转义的,所以从

(localdb)\\MSSQLLocalDB...

(localdb)\\\\MSSQLLocalDB...

但即使在删除额外的反斜杠后问题仍然存在)

更新:当连接字符串移动到Windows级别环境变量时,它工作正常。使用Visual Studio环境变量时似乎只是一个问题。

热门答案

我建议您使用DesignTimeContextFactory类进行迁移:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    AmpContext IDesignTimeDbContextFactory<MyContext>.CreateDbContext(string[] args)
    {
        var connectionString = ConfigHelper.GetConnectionString();

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

        return new AmpContext(optionsBuilder.Options);
    }
}

对我来说,GetConnectionstring就像这样,我在整个应用程序中使用它(对于我的Web API项目和集成测试):

public class ConfigHelper
{
    /// <summary>
    /// Gets the connectionstring from the appsettings.databasestring.json file in the solution root if there is no environment variable to be found
    /// </summary>
    /// <param name="solutionBasePath">Optional to not auto resolve the solution base path</param>
    /// <returns></returns>
    public static string GetConnectionString(string solutionBasePath = null)
    {
       //how to set it on IIS on the server: https://stackoverflow.com/a/36836533/1343595
        var environmentString = Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MyContextDb");

        if (!string.IsNullOrEmpty(environmentString))
            return environmentString;

        if(!string.IsNullOrEmpty(solutionBasePath))
            return GetStringFromConfig(Path.Combine(solutionBasePath, "appsettings.databasestring.json"));

        var filePath = Path.Combine(GetSolutionBasePath(), "appsettings.databasestring.json");

        return GetStringFromConfig(filePath);
    }

    private static string GetStringFromConfig(string filePath)
    {
        IConfigurationRoot config = new ConfigurationBuilder()
            .AddJsonFile(filePath) //you can change the value of the connectionstring in the appsettings file and add it to gitignore so the change will not effect others
            .Build();

        var connectionString = config.GetConnectionString("MyContextDb");
        return connectionString;
    }

    /// <summary>
    /// Gets the current soution base path
    /// </summary>
    /// <returns></returns>
    public static string GetSolutionBasePath()
    {
        var appPath = PlatformServices.Default.Application.ApplicationBasePath;
        var binPosition = appPath.IndexOf("\\bin", StringComparison.Ordinal);
        var basePath = appPath.Remove(binPosition);

        var backslashPosition = basePath.LastIndexOf("\\", StringComparison.Ordinal);
        basePath = basePath.Remove(backslashPosition);
        return basePath;
    }
}


Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因