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

时间:2017-01-26 03:50:39

标签: c# asp.net entity-framework asp.net-core 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环境变量时似乎只是一个问题。

2 个答案:

答案 0 :(得分:0)

如果在(localdb)之后删除双反斜杠,那么它只有一个反斜杠。

所以一旦你在环境变量中纠正了它,它应该是这样的:

Server=(localdb)\MSSQLLocalDB...

答案 1 :(得分:0)

I suggest you use a DesignTimeContextFactory class for the migrations:

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);
    }
}

the GetConnectionstring for me is like this and I use it throughout my application (that is for my Web API project and for integration tests):

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;
    }
}