System.Configuration.ConfigurationManager.ConnectionStrings has no connection string configured

谁都会走 提交于 2020-01-04 06:04:53

问题


Whenever I try to run anything in my C# code I get the following error:

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

and it happens in the following code.

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);

So System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"] is null. I can't really find anything about it, one question that might be related: How to fix "The ConnectionString property has not been initialized" suggests that something might be wrong with the config file. At this moment I'm afraid I somehow accidentally deleted a config file.

Also, just read this in the documentation:

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

It contains the default values, so I'm inclined it's in a config file that I must have accidentally removed.

If I'm right, I don't know which one or where it should be, and what it should contain. If I'm wrong, I have no clue where it comes from. So where is the System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"] set? And/or how can I fix this issue?


回答1:


Connection strings in .NET come from a config file - either app.config for console / Windows apps or web.config for a Web app.

You can add a new config file to your project by right-clicking the project and adding the correct file, and make sure you have the following section in that config file:

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

And of course you'd need to replace the connection string with something that is appropriate for your environment (e.g. replace databasename with your database name).




回答2:


It could be that your project is not referencing the right config file. You should only have one app.config file.

You need to make sure you are adding your app.config to the project which is generating .exe file.

Go to your output directory and open the .exe.config file. Do the contents match what you expected?



来源:https://stackoverflow.com/questions/10761193/system-configuration-configurationmanager-connectionstrings-has-no-connection-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!