Saturday, November 17, 2012 10:08 PM
In an existing C# 2010 application, I want to add linq to sql tatements to connect to a sql server 2008 database. When I setup this linq to sql database, I want to be able to setup the connections to the database using the app.config file.
I have read that when you setup the database connection this way, the default database is used. Basically this is ok when you database on the same database. However, when you move from a unit testing database to a user acceptance and/or a production database there is a problem since the database connection is hard coded in the aqpplication.
Thus can you tell me and/or show me with code how to prevent this problem from occuring?
Saturday, November 17, 2012 10:36 PM
In your connection string use either "Inital Catalog=DatabaseName" or "Database=DatabaseName".
Hope this helps
Sunday, November 18, 2012 5:38 AMI do not see how using the initial catalog will fix my problem. Can you explain your answer ro me?
Sunday, November 18, 2012 3:45 PM
Perhaps I don't get what you need. You can create a connection string in your app.config file. Initial Catalog will point to the database you want to use. If this is not what you need, what do you want?
Sunday, November 18, 2012 5:33 PM
The way you can do this is as follows. In the app.config file add a new connection pointing to the server you want to connect to as shown in the app.config file settings shown below.
<connectionStrings> <!-- The Default Connection String --> <add name="UnitTesting.NORTHWND" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=NORTHWND.MDF;Integrated Security=True" providerName="System.Data.SqlClient" /> <!-- The New Connection String --> <add name="Production.NORTHWND" connectionString="Data Source=myServerName\myInstanceName;Initial Catalog=NORTHWND.MDF;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
Then in the program select the connection string you want to use by for example showing what servers you can connect to from the app.config file by using a statement as follows:
var allConnstr = ConfigurationManager.ConnectionStrings;
Which returns a array of IDbConnection, display it to the user and let the user select the server and use that value to create the DataContext as follows :
var ctx = new DataClasses1DataContext(allConnstr[i].ToString());
where i in the above statement is the element of the array the user selected.
You will also need to add the following using statement, using System.Configuration;, as well as adding a reference to the following dll, System.Configuration.dll.
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
- Marked As Answer by scamper_cat Monday, November 19, 2012 3:54 AM