3

每当我尝试在 C# 代码中运行任何内容时,都会收到以下错误:

System.InvalidOperationException was unhandled by user code
Message=No connection string configured

它发生在以下代码中。

if (System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"] == null)
{
     throw new System.InvalidOperationException("No connection string configured");
}

connectionString = string.Format("{0};Application Name={1}", System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"].ConnectionString, this.applicationName);

System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"]空也是如此。我真的找不到任何关于它的东西,一个可能相关的问题:How to fix "The ConnectionString property has not been initialized"表明配置文件可能有问题。此刻恐怕我不小心删除了一个配置文件。

另外,只需在文档中阅读:

Returns a ConnectionStringSettingsCollection object that contains the contents of the ConnectionStringsSection object for the current application's default configuration. 

它包含默认值,所以我倾向于它位于我一定不小心删除的配置文件中。

如果我是对的,我不知道它应该在哪一个或在哪里,以及它应该包含什么。如果我错了,我不知道它来自哪里。那么 System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"] 设置在哪里呢?和/或我该如何解决这个问题?

4

2 回答 2

8

.NET 中的连接字符串来自配置文件 - app.config 用于控制台/Windows 应用程序或 web.config 用于 Web 应用程序。

您可以通过右键单击项目并添加正确的文件来将新的配置文件添加到您的项目中,并确保该配置文件中有以下部分:

<configuration>
  <connectionStrings>
    <add name="DBContext" connectionString="data source=.\SQLEXPRESS;Initial Catalog=databasename;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>
  ...
</configuration>

当然,您需要将连接字符串替换为适合您环境的内容(例如,将 databasename 替换为您的数据库名称)。

于 2012-05-25T20:57:12.933 回答
2

可能是您的项目没有引用正确的配置文件。您应该只有一个 app.config 文件。

您需要确保将 app.config 添加到生成 .exe 文件的项目中。

转到您的输出目录并打开 .exe.config 文件。内容是否符合您的预期?

于 2014-09-30T14:16:57.943 回答