【问题标题】:System.Configuration.ConfigurationManager.ConnectionStrings has no connection string configuredSystem.Configuration.ConfigurationManager.ConnectionStrings 没有配置连接字符串
【发布时间】:2012-05-25 20:50:45
【问题描述】:

每当我尝试在我的 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" 表明配置文件可能有问题。此刻恐怕我不小心删除了一个配置文件。

另外,请阅读documentation

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

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

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

【问题讨论】:

  • " 所以我倾向于它在我一定不小心删除的配置文件中。"对,就是那样。你有你的配置备份吗?

标签: c# visual-studio configuration connection-string default


【解决方案1】:

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

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

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

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

【讨论】:

  • 有点痛苦,但总比不得不使用注册表好。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多