Using the Web.Config connection string with LINQ to SQL
by Tim Banks
When updating a project to use LINQ to SQL, I found an issue with deploying to multiple environments. Â Each environment (development, staging, live) had its’ own database associated with this. Â Since I had the .dbml in another assembly, it was only reading from the app.config in the assembly it resided in. Â I was storing the database connection string in the web.config of the project so I thought it would be nice to just use that instead of the app.config.
The first thing I needed to do was to keep the .dbml file from reading from the app.config. Â After opening up the .dbml file, I opened the properties window for the file. Â In the properties window, there is a setting for “Connection”. Â In the “Connection” dropdown I selected the “(None)” selection. Â That keeps the .dbml file from accessing the app.config for the database connection string.
??
Now I needed to get my MainDataContext to use the Web.Config connection string. Â For this I created a partial class for my MainDataContext and created a constructor that passed the connection string from the Web.Config.
public partial class MainDataContext
{
public MainDataContext()
: base(System.Configuration.ConfigurationManager.ConnectionStrings["Database.connection.string.from.web.config"].ToString(), mappingSource)
{
OnCreated();
}
}
Now when I deploy to different environments the .dbml file is accessing the correct database instead of the same one from the app.config.
Tags: ASP.NET, C#, LINQ, LINQ to SQL, csharp, web.config
« Converting Names to Mixed Case/Camel Case in SQL Server Export to Excel Class »

June 11th, 2010 at 8:26 pm
[...] can read the whole article over at http://lanitdev.wordpress.com/2010/06/11/using-the-web-config-connection-string-with-linq-to-sql/ Share and [...]
June 12th, 2010 at 8:25 am
[...] Using the Web.Config connection string with LINQ to SQL « The … [...]
November 27th, 2011 at 12:16 am
Thanks for the info!…
[...]Foliotek Development Blog » Blog Archive » Using the Web.Config connection string with LINQ to SQL[...]…