Reputation: 73
I have developed an ASP.net web application which interacts with sqlserver database. For database related task like ADO.net. Connection string gets loaded from web.config file. connection string loading code is written below
public DataBaseCache()
{
CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//etc
}
My web.config file is below
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=F:\ProjectApplication6-3\ProjectApplication\App_Data\ProjectDatabases.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Now Problem is that if i save my Visual studio project file to other drive i need to change my connection string in web.config file in this example it is in Drive F. Please guide me how to avoid this copy paste each time i save application to various drives and code does it automatically.? regards
Upvotes: 0
Views: 4695
Reputation: 2562
Put the database in the App_Data directory in your project and use:
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ProjectDatabases.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
When you move your project to a different drive/computer, and SQL Express is installed, your project should be able to attach to your database.
This other question is similar to yours and may provide additional insight.
Note I added "|DataDirectory|" to the connection string
Upvotes: 2
Reputation: 8410
change your web.config
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename={0}ProjectApplication6-3\ProjectApplication\App_Data\ProjectDatabases.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
and then in your code
public DataBaseCache()
{
string rootPath="F:\";
CS = String.Format(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString, rootPath);
//etc
}
Upvotes: 0