appsettings.json中ConnectionString中的SQL别名问题

时间:2017-07-26 12:40:39

标签: asp.net-core app-config entity-framework-core

在我的appsettings.json中,当我使用此代码段时:

"ConnectionStrings": {
    "CssDatabase": "Server=BLUEJAY\\MSSQLSERVER2014;Database=CSS;Trusted_Connection=True;" 
}

我可以按预期连接到数据库......没问题。

然而,当我改变它以使用SQL Alias(CSSDB)时,如下所示:

"ConnectionStrings": {
    "CssDatabase": "Server=CSSDB;Database=CSS;Trusted_Connection=True;" 
}

它已正确配置,因为我可以在SSMS中使用此SQL别名连接到数据库而不会出现问题。

返回:

The server was not found or was not accessible. Verify that the
instance name is correct and that SQL Server is configured to allow
remote connections. (provider: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server) --->
System.ComponentModel.Win32Exception: The network path was not found

我正在使用Microsoft.EntityFrameworkCore

1 个答案:

答案 0 :(得分:17)

由于有关存储在Windows注册表中的SQL别名的信息,Microsoft团队决定放弃对.NET Core的支持,因为它不是跨平台解决方案。这里是link to discussion about it

然而,有一些解决方法(也来自此讨论),对我来说很好,但请记住它仍然是Windows唯一的解决方案:

var builder = new SqlConnectionStringBuilder(config.ConnectionString);

var key = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86"
    ? @"HKEY_LOCAL_MACHINE\SOFTWARE\ Microsoft\MSSQLServer\Client\ConnectTo"
    : @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer\Client\ConnectTo";

var newSource = (string)Microsoft.Win32.Registry.GetValue(key, builder.DataSource, null);
if (newSource != null)
    builder.DataSource = newSource.Substring(newSource.IndexOf(',') + 1);

config.ConnectionString = builder.ConnectionString;

如果你没有将ConnectionString存储在不同的C#类中,你可以像我在下面那样将builder.ConnectionString传递给ConfigureServices方法中的服务:

services.AddDbContext<AppDbContext>(
                opt => opt.UseSqlServer(builder.ConnectionString));