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

Eri*_*ric 7 app-config entity-framework-core asp.net-core

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

"ConnectionStrings": {
    "CssDatabase": "Server=BLUEJAY\\MSSQLSERVER2014;Database=CSS;Trusted_Connection=True;" 
}
Run Code Online (Sandbox Code Playgroud)

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

但是,当我更改它以使用SQL别名(CSSDB)时,如下所示:

"ConnectionStrings": {
    "CssDatabase": "Server=CSSDB;Database=CSS;Trusted_Connection=True;" 
}
Run Code Online (Sandbox Code Playgroud)

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

返回:

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
Run Code Online (Sandbox Code Playgroud)

我在用Microsoft.EntityFrameworkCore.

use*_*704 21

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

但是有一些解决方法(也来自这个讨论),对我来说很好,但请记住它仍然是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;
Run Code Online (Sandbox Code Playgroud)

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

services.AddDbContext<AppDbContext>(
                opt => opt.UseSqlServer(builder.ConnectionString));
Run Code Online (Sandbox Code Playgroud)

  • 我已将此代码封装在库/NuGet 包中:https://github.com/droyad/SqlAlias (5认同)
  • 只是浪费了整个下午试图弄清楚为什么我的连接字符串突然不起作用...... (2认同)