加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – appsettings.json中ConnectionString中的SQL别

发布时间:2020-12-16 03:42:43 所属栏目:asp.Net 来源:网络整理
导读:在我的appsettings.json中,当我使用此代码段时: "ConnectionStrings": { "CssDatabase": "Server=BLUEJAYMSSQLSERVER2014;Database=CSS;Trusted_Connection=True;" } 我可以按预期连接到数据库……没问题. 但是,当我更改它以使用SQL别名(CSSDB)时,如下所
在我的appsettings.json中,当我使用此代码段时:

"ConnectionStrings": {
    "CssDatabase": "Server=BLUEJAYMSSQLSERVER2014;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的支持,因为它不是跨平台解决方案.这里 link to discussion about it.

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

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方法中的服务,就像我在下面所做的那样:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读