【问题标题】:Entity Framework Core Connection String - Environment Variable实体框架核心连接字符串 - 环境变量
【发布时间】:2017-01-26 03:50:38
【问题描述】:

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

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

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

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

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

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

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

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

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

(localdb)\\MSSQLLocalDB...

(localdb)\\\\MSSQLLocalDB...

但即使删除多余的反斜杠,问题仍然存在)

更新: 当连接字符串被移动到 Windows 级别的环境变量中时,它可以正常工作。似乎只有在使用 Visual Studio 环境变量时才会出现问题。

【问题讨论】:

  • 试着加一个反斜杠
  • 那是我在上面的“注释”中提到的,但没有帮助。
  • 我认为它与 Project.Json 有关,请检查您是否在启动应用程序或数据库层中有注释行(如果有的话)。 JSON 文件中不能有任何注释行
  • 我把所有的cmet都去掉了,以后可能会出问题,但是这个问题没有解决。

标签: c# asp.net entity-framework asp.net-core entity-framework-core


【解决方案1】:

如果您删除(localdb) 之后的双反斜杠,它会起作用,以便只有一个反斜杠。

因此,一旦您在环境变量中更正了它,它应该看起来像这样:

Server=(localdb)\MSSQLLocalDB...

【讨论】:

  • @MonteChristo Yarrgh 正试图帮助你,我建议你下次有人这样做时你的回答要温和
【解决方案2】:

我建议您使用 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多