如何访问连接字符串并连接到数据库

时间:2019-07-16 16:56:53

标签: c# sql-server entity-framework api connection-string

因此,我正在从事一个涉及外部API和数据库的项目。该API使用称为Add In的特定于API的项目类型,并被编译为库,然后添加到API的源程序中。这样,我可以在程序的插件中创建自己创建的“动作”,然后从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);

  }

1 个答案:

答案 0 :(得分:2)

使用下面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);
  }
相关问题