The ConnectionString property has not been initialized error

随声附和 提交于 2020-01-03 05:52:05

问题


I'm using an asp.net web application with a MySql DB, with the following connetcion string the web.config:

<add name="techConnectionString" connectionString="server=vm-tmysql01;User Id=user;database=tech;password=pass" providerName="MySql.Data.MySqlClient"/>

And this is the code I'm using the get the connection string from the web.config:

System.configuration.configurationmanaget.connectionstrings["techConnectionString"].connectionstring;

For some reason I get the error:

The ConnectionString property has not been initialized. An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

And the stack trace is:

[InvalidOperationException: The ConnectionString property has not been initialized.]
   System.Data.SqlClient.SqlConnection.PermissionDemand() +6316916
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6296606
   System.Data.SqlClient.SqlConnection.Open() +300

I'm able to connect to the DB via the Data Sources in Visual Studio and took the ConnectionString from there. I really need some help with it, is there any problem with my connection string?


回答1:


The problem wasn't with the connetion string, it was with the c# code trying to reach it from the web.config file.

i was trying to use:

System.Configuration.ConfigurationManager.ConnectionStrings["techConnectionString"].ConnectionString;

But i needed to use:

System.Web.Configuration.WebConfigurationManager.ConnectionStrings["techConnectionString"].ConnectionString;



回答2:


change connection string as

 <connectionStrings>
    <add name="techConnectionString" connectionString="SERVER=vm-tmysql01; DATABASE=tech; UID=user; 
PASSWORD=pass" providerName="MySql.Data.MySqlClient"/>
 </connectionStrings>

and you can get connection using System.Configuration ( you need to add reference to System.Configuration)

var constring =ConfigurationManager.ConnectionStrings["techConnectionString"].ConnectionString;


来源:https://stackoverflow.com/questions/19355946/the-connectionstring-property-has-not-been-initialized-error

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