【发布时间】:2019-07-16 16:56:53
【问题描述】:
所以我正在处理一个涉及外部 API 和数据库的项目。此 API 使用称为 Add In 的 API 特定项目类型,并编译为库,然后添加到 API 的源程序中。这样,我可以在程序的 Add in 中创建自己创建的“操作”,并从 MVC Web 项目远程调用它们。此操作还包含与更新服务器上上传的数据库相关的代码。当我尝试远程调用此操作时,我会在添加插件的应用程序中收到此错误:
A network-related or instance-specific error occurred while establishing a connection to SQL server. 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
我得到了导师的帮助,并解决了 Add Ins app.config 中的连接字符串问题。它被验证是正确的(我可以直接从 web MVC 项目访问数据库)。我尝试在项目中使用var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; 读取连接字符串,但找不到。调用该操作时,我得到一个空对象引用错误。
这是我的插件应用配置:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=PROD4W\PROD4W;Initial Catalog=EplanInterfaceDb;user id = SomeID; password=SomePassword;Integrated Security=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
这是我的 add In 项目中与数据库相关的代码:
//Here is where my mentor tried to pull the connection string from the //app.config.This is where the object reference error
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//Output the connection string to the screen on outside app
new Decider().Decide(EnumDecisionType.eOkDecision, "Connection: " + connectionString, "", EnumDecisionReturn.eOK, EnumDecisionReturn.eOK);
//Access the database and add a test
using (var context = new DataContext())
{
//Throws network related error mentioned above
context.Macros.Add(new Macro { Name = "test" });
context.SaveChanges();
//Output to the screen if the savechanges was successful
new Decider().Decide(EnumDecisionType.eOkDecision, "Save Changes Called ", "", EnumDecisionReturn.eOK, EnumDecisionReturn.eOK);
}
【问题讨论】:
-
运行时未使用类库项目的应用配置。只有执行程序的 app.config。所以你需要在那里定义适当的连接字符串。
-
问题是我无法在他们的程序中定义它。他们的程序只是接收我们创建的 Addin.Dll 并将其作为“宏”导入他们的程序,基本上可以远程或直接通过他们的程序运行。因此,即使在这种情况下,您是否认为需要添加连接字符串?我们最好只使用 SQLConnection() 类并手动写出连接字符串吗? (我知道不好的做法,但这都是内部的)。 @梅森
-
您可以获得连接字符串,但它对您来说是有意义的。无论是 app.config,还是寻找环境变量、特定位置的文件或硬编码。只需了解您这样做所做的权衡,并确保它们是可以接受的。如果您确实选择将它放在 app.config 中,则它必须在执行程序的 app.config 中,或者更高级别的配置中,例如 machine.config。
标签: c# sql-server entity-framework api connection-string