Reputation: 66535
When I start my application I get: The ConnectionString property has not been initialized.
Web.config:
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User Id=myuser;Password=mypassword;" />
</connectionStrings>
The stack being:
System.Data.SqlClient.SqlConnection.PermissionDemand() +4876643
System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
I'm fairly new to .NET and I don't get this one. I found a lot of answers on Google, but none really fixed my issue.
What does that mean? Is my web.config bad? Is my function bad? Is my SQL configuration not working correctly (I'm using sqlexpress)?
My main problem here is that I'm not sure where to start to debug this... anything would help.
EDIT:
Failling code:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.AppSettings["ConnectionString"],
CommandType.Text,
sqlQuery,
sqlParams);
sqlQuery is a query like "select * from table". sqlParams is not relevant here.
The other problem here is that my company uses MySQLHelper, and I have no visibility over it (only have a dll for a helper lib). It has been working fine in other projects, so I'm 99% that the error doesn't come from here.
I guess if there's no way of debuging it without seeing the code I'll have to wait to get in touch with the person who created this helper in order to get the code.
Upvotes: 68
Views: 498724
Reputation: 1
I've had the same problem and it fixed by renaming the ConnectionStrings to DefaultConnection and it worked
as I explained I renamed this section to DefaultConnection
Upvotes: 0
Reputation: 11
sometimes it's better to change your connection name in asp .net core , for example you can change Defaultconnection to AppDb
Upvotes: 0
Reputation: 1
I had the same issue and maybe my solution will help anyone, as this was silly mistake but not so easy to debug. So in my case I was creating some db configuration service that will have more than one context like this:
public SecondContext SecondContextName { get; private set; }
public FirstContext FirstContextName { get; private set; }
public DatabaseConfigurationService(ClientFactory clientFactory)
{
FirstContextName = clientFactory.ServiceProvider.GetService<FirstContext>();
SecondContextName = clientFactory.ServiceProvider.GetService<SecondContext>();
}
The issue was that while trying to initiate services like this:
var configuration = BuildConfiguration();
services.AddDbContext<FirstContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("FirstContextName"), opt => opt.CommandTimeout(360)));
services.AddDbContext<SecondContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("SecondContextName")));
return configuration;
I didn't notice that the two parameters that was passed in UseSqlServer method are in fact combined to one option value. So when my db context constructor looked like this:
public FirstContextName(DbContextOptions<FirstContext> options, IConfiguration configuration)
: base(options)
{
}
everything landed to default constructor not initiating connection string properly.
Upvotes: 0
Reputation: 488
Resolved this in VS-2022 .NET 6.0 platform. Though many answers essentially point in the right direction i.e this has to be definitely issue with how you are setting configs in your AppSettings.json file. I came across a very peculiar issue in my case which probably I will describe here so it could help someone potentially. Check below screenshot:
Let us say you have a appsettings.(something).json within your appsettings.json(some thing like a tree structure). Your connection string change is in appsettings.(something).json & not in appsettings.json than there may lie the issue in your local. You need to update the connection strings details in your appsettings.json file. This helped my issue. After this, I ran the 'dotnet ef database update'. It got executed & the tables got created using code first approach in EF core.
Upvotes: 0
Reputation: 1
In my experience, when you see this error in your appsettings.json
file, you should check your letters. For example, I have written connectionString
instead of ConnectionString
. So, be careful when you write keywords.
Upvotes: 0
Reputation: 1
In my case to connect to DB I used connections string in .json file. Some how I changed
ConnectionString
to
ConnectionStrings
(added 's') and everything is fine.
Upvotes: 0
Reputation: 31
ConnectionString at Appsetting.json & Program.cs should not be same.
Upvotes: 1
Reputation: 1
IN the startup.cs provide ConnectionStrings
for eg:
services.Configure<Readconfig>(Configuration.GetSection("ConnectionStrings"));
Upvotes: 0
Reputation: 21
I stumbled in the same problem while working on a web api Asp Net Core project. I followed the suggestion to change the reference in my code to:
ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString
but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".
To fix the problem I had to download the package System.Configuration.ConfigurationManager
using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)
Upvotes: 1
Reputation: 1066
I couldn't fix this exact problem nor have time to investigate, but in my case, it was related to Windows Server 2012 R2 or the framework version. The exact same code, app and config file worked flawlessly on other machines running other Windows versions. Tryed with at least the consumer versions (Windows 8, 10 and 11). Just Windows Server 2012 refused with the error in
System.Data.SqlClient.SqlConnection.PermissionDemand()
Upvotes: 0
Reputation: 11
In my case, I missed a single letter in the word "ConnectionStrings" so it didn't match with the appsettings.json properties thus it gave me this error. An error could not be as deep as you may think. Start debugging by spelling mistakes.
Upvotes: 0
Reputation: 49
If you tried every answer mentioned above then there is the possibility that you are creating a new SQL connection based on the wrong sqlconnection check condition. Below is the scenario :
The common method to return new SQL connection if it is not previously initialized else will return the existing connection
public SqlConnection GetSqlconnection()
{
try
{
if(sqlConnection!=null)
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
// return sqlConnection;
}
//here two methods which are using above GetSqlconnection() method
public void getUser()
{
//call to GetSqlconnection() method to fetch user from db
//connection.open()
//query execution logic will be here
//connection.close() <---here is object state changed --->
}
public void getProduct()
{
//call to GetSqlconnection() method with no connection string properties
//connection.open() ; <--- here exception will be thrown as onnectionstring-property-has-not-been-initialized
//query execution logic will be here .
//connection.close().
}
As soon as you close the connection in getUser() method there will two change in sqlconnection object 1.Status changed from 'Open' to 'Close' 2.ConnectionString property will be change to ""
hence when you call GetSqlconnection() method in getProduct() , accroding to if-Condition in GetSqlconnection() ,it will return the existing object of sqlConnection but with status as 'Closed' and ConnectionString as " ". thus at connection.open() it will throw exception since connectionstring is blank.
To solve this problem while reusing sqlConnection we should check as below in GetSqlconnection() method :
try
{
if(sqlConnection==null || Convert.ToString(sqlConnection.State)=="Closed")
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
Upvotes: 1
Reputation: 503
This what worked for me:
var oSQLConn = new
SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["Conn1"].ToString()
);
Upvotes: 0
Reputation: 1
I found that when I create Sqlconnection = new SqlConnection()
,
I forgot to pass my connectionString
variable. So that is why I changed the way I initialize my connectionString
(and nothing changed).
And if you like me just don't forget to pass your string connection into SqlConnection
parameters.
Sqlconnection = new SqlConnection("ConnString")
Upvotes: 0
Reputation: 26190
You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).
If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);
If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.
Post your code (for the databound element and the web.config to be safe) and we can take a look at it.
EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
(if ConnectionString is the name of your connection string.)
Upvotes: 20
Reputation: 1946
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"]
would be looking in the AppSettings
for something named ConnectionString
, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized
, because it is looking for an initialized property of AppSettings
named ConnectionString
.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString
instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
Upvotes: 48
Reputation: 1
Use [] instead of () as below example.
SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
DataTable data = new DataTable();
DataSet ds = new DataSet();
Upvotes: -2
Reputation: 38882
The connection string is not in AppSettings.
What you're looking for is in:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...
Upvotes: 5