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?
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:
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).
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?