實體框架核心連接字符串 - 環境變量

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合法嗎? 是的,了解原因