【发布时间】:2019-06-26 08:35:32
【问题描述】:
我正在使用 .NET Core 和 EF Core(均为 v3.0)开发控制台应用程序;我需要使用从另一个类生成的字符串来启动我的 DbContext。
DbContext 文件
public Arta_LuniaDBContext() { }
public Arta_LuniaDBContext(DbContextOptions<Arta_LuniaDBContext> options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(DataServices.ConnectionString);
}
数据服务类
public static string ConnectionString { get { return GetConnectionData(); } }
private static string GetConnectionData()
{
/// Sets the Server name, Database, UserId and Password.
string Server, Database, UserId, Password;
/// Sets the separator.
string Separator = ";";
/// Connection string [internal].
string ArtaConn = null;
/// Loads Settings.xml
XmlDocument xDoc = new XmlDocument();
xDoc.Load("Settings.xml");
/// Gets the XmlNode: DataSource
XmlNodeList xSource = xDoc.GetElementsByTagName("DataSource");
for (int i = 0; i < xSource.Count; i++)
{
/// Sets the Server name.
Server = "Server=" + xSource[i].Attributes["Server"].Value + Separator;
/// Sets the Database.
Database = "Database=" + xSource[i].Attributes["Database"].Value + Separator;
/// Sets the User id.
UserId = "User id=" + xSource[i].Attributes["UserId"].Value + Separator;
/// Sets the Password.
Password = "Password=" + xSource[i].Attributes["Password"].Value + Separator;
/// Builds the connection string.
ArtaConn = Server + Database + UserId + Password;
Colorful.Console.WriteLine(ArtaConn, System.Drawing.Color.Yellow);
// I'm using this line to test the output.
}
/// Returns~
return ArtaConn;
}
Settings.xml
<!-- Sets the Database ConnectionString -->
<DataSource Server="IP_ADDRESS\\INSTANCE" Database="DbName" UserId="MyUser" Password="MyPassword" />
ConsoleWrite 行显示我的输出为:
Server=IP_ADDRESS\\INSTANCE;Database=DbName;User id=MyUser;Password=MyPassword;
这个字符串对我来说似乎没问题,但是当我尝试连接到数据库时,我收到以下错误:
System.Data.SqlClient.SqlException (0x80131904):网络相关或 建立连接时发生特定于实例的错误 SQL 服务器。服务器未找到或无法访问。核实 实例名称正确且 SQL Server 配置为 允许远程连接。 (提供者:SQL 网络接口,错误:26 - 定位服务器/指定实例时出错)
很奇怪,如果我设置的话:
optionsBuilder.UseSqlServer("IP_ADDRESS\\INSTANCE;Database=DbName;User id=MyUser;Password=MyPassword;");
我可以毫无问题地连接……
有什么办法可以解决吗?提前致谢。
[编辑] 修复它; 更改:
<DataSource Server="IP_ADDRESS\\INSTANCE" Database="DbName" UserId="MyUser" Password="MyPassword" />
收件人:
<DataSource Server="IP_ADDRESS\INSTANCE" Database="DbName" UserId="MyUser" Password="MyPassword" />
【问题讨论】:
-
您是否在问题中提供了实际密码?
-
如果您想要一个不硬编码代码中的连接字符串的简单解决方案,您可以通过配置变量存储硬编码的连接字符串来组合上述两种方法,然后访问该配置变量在您对 optionsBuilder.UseSqlServer 的调用中。另外,您真的不应该将整个连接字符串(包括密码)发布到本网站上供所有人查看!
-
糟糕,已修复连接密码和详细信息。 :p
-
该密码在历史记录中仍然可用。最好改一下。
-
您可能对此信息感兴趣:如何删除历史记录。另请注意@jdv:更改密码。 meta.stackexchange.com/questions/86195/…
标签: c# sql-server entity-framework .net-core