Wednesday, 5 January 2011

LINQ to SQL - How to put Connectionstring in web.config

When you add a LINQ to SQL dataclasses(.dbml file) to the project the connection string is automatically configured for you when your dragging the tables. However in practice you need to take the connection string settings outside the datacontext file and put it the config file. This is useful particularly when you've got the project on different servers (dev, staging). 
To do this all you need to is:
1- Open the .dbml file in the designer, right click on somewhere on the blank screen (not on the objects/tables) to open the properties window and update the connection to look like this: 
And then:
2- Create a partial class for your dataContext and only a constructor in it:
public partial class TestDataContext 
   public TestDataContext () : base(ConfigurationManager.ConnectionStrings["TestKey"].ConnectionString, mappingSource)
3- Update the connection string section in the config file with the new key:

For more info please refer to the following links:

No comments:

Post a Comment