appsettings.json中ConnectionString中的SQL別名問題

app-config asp.net-core entity-framework-core

在我的appsettings.json中,當我使用這個片段時:

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

我可以按預期連接到數據庫......沒問題。

但是,當我更改它以使用SQL別名(CSSDB)時,如下所示:

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

它已正確配置,因為我可以在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

我正在使用Microsoft.EntityFrameworkCore

一般承認的答案

由於有關存儲在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;

如果你沒有將ConnectionString存儲在不同的C#類中,你可以將builder.ConnectionString傳遞給ConfigureServices方法中的服務,就像我在下面所做的那樣:

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow