Linq to Sql: Change connectionstring to load from Web.config

Update 20 may 2009: New easy sollution

Set the Connection -> Application Settings property True. This will generate a connection string in your app.config.

 

Copy this connection string to your web.config and your all set!

 

================================================================= 

Old post: 

If you want to use your connectionstring from the web.config with Linq to Sql (dbml) you have to add the following partial class to your project:

[code:c#]

namespace Your.Namespace
{
  partial class yourDataContext
  {
    partial void OnCreated()
    {
       ConnectionStringSettings s = ConfigurationManager.ConnectionStrings["YourConnectionString"];
       if (s != null)
         Connection.ConnectionString = s.ConnectionString;
    }
  }
}

[/code]

Don't forget to change the Your.Namespace, yourDataContext and YourConnectionString to fit your project.

Hope this helps.

2 Replies to “Linq to Sql: Change connectionstring to load from Web.config”

Leave a Reply

Your email address will not be published. Required fields are marked *