且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-16 10:46:38

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

Since information about SQL Aliases stored in Windows registry the Microsoft team decided to drop its support in .NET Core, because it is not cross-platform solution. Here the link to discussion about it.

但是有解决方法(也来自此讨论),对我来说效果很好,但请记住,它仍然是仅适用于 Windows 的解决方案:

However there is workaround(also from this discussion), which worked fine for me, but bear in mind it is still Windows only solution:

var builder = new SqlConnectionStringBuilder(config.ConnectionString);

var key = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86"
    ? @"HKEY_LOCAL_MACHINESOFTWARE MicrosoftMSSQLServerClientConnectTo"
    : @"HKEY_LOCAL_MACHINESOFTWAREWOW6432NodeMicrosoftMSSQLServerClientConnectTo";

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 方法中的服务:

If you not storing ConnectionString in the distinct C# class you can just pass the builder.ConnectionString to services in ConfigureServices method like I did below:

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