Point connectionstring in dbml to app.config

This is more like an extension to @Alex’s answer.

Step 1 : Set the connection property of your .dbml file to “none”.

enter image description here

Step 2 : Create a new separate partial class with the same name as that of the existing partial class for the .dbml file. And set the connectionString property by using the parameterless constructor.

public partial class DataClassesDataContext
{
  public DataClassesDataContext() : base(ConfigurationManager.ConnectionStrings["Dev-connString"].ConnectionString)
  {
    OnCreated();
  }
}

Step 3 : Almost Done ! Lastly you need to define your connectionString in your app.config file, as shown below.

<connectionStrings>

  <add
  name="Dev-connString"
  connectionString="Data Source=yasser-home;Initial Catalog=pp;Persist Security Info=True;User ID=sa;Password=gogole"
  providerName="System.Data.SqlClient" />

</connectionStrings>

You can now easily change the connectionString from the app.config file without having to re-compile your code, which would be the case otherwise.

Why did I create a seperate partial class ? Can’t I edit the existing Dbml.designer.cs file ?

Don’t modify Dbml.designer.cs file manually, because it will be rewritten when you add/edit/delete a table, stored proc etc.

Leave a Comment

tech