Pieter Brinkman Blog

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

1 min readpieterASP.NetlinqSQL Server

Update 20 may 2009: New easy solution

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 you're all set!

Copy this connection string to your web.config and you're 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.