c# - 如何访问连接字符串并连接到数据库
问题描述
所以我正在做一个涉及外部 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);
}
解决方案
使用 Mason 在下面推荐的内容,您可以简单地对连接字符串进行硬编码,而不是从 app.config 中提取它(如果它给您带来问题)。这是一个示例:
var connectionString = "Hard code connection string";
//Make sure your DataContext has a constructor that takes in a connection string
using (var context = new DataContext(connectionString))
{
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);
}
推荐阅读
- python - 有没有办法控制使用 python 添加 PDF 书签的位置?
- r - 用矩阵泛化函数
- pandoc - 将html目录转换为markdown?Html 在一个父目录的多个文件夹中
- python - 如何使用 xbbg 下载刻度数据切片?
- facebook - 将 Google Tag Manager 连接到 Facebook,不会发布?
- python - 为什么这个对文件中的字符进行计数的函数总是返回 0?
- windows - 如果低于特定 Windows 版本,如何检查 Windows 版本并显示 MessageBox?
- python - 如何从python中的目录打印单个文件
- node.js - Firebase Admin SDK Node.js 在实时数据库中的块读取和写入
- node.js - 如何从 getServerSideProps 访问 NextJS 响应正文?