Sunday, November 2, 2008

LINQ Connection String - app.config vs web.config

  • When you are using Linq to SQL, if you have your dbml in a class library project and you drag and drop a database table from the Server Explorer onto the dbml designer, VS2008 will automatically create the app.config for you which contains the connectionstring.
  • If you have a web application project which references the Linq class library and you want to put the connectionstring in the web.config, here is how:

1. Remove the default constructor in the dbml designer class. Create a partial class for the datacontext class which contains the constructor to re-set the connectionstring.

2. You need to set the dbml's connection to none whenever new stuff has been dragged onto the design surface.

3. Put the connectionstring in the web.config

Sample Code:

Imports System.Configuration


'We don't want to use app.config to store connectionstring, we need to use web.config


'So we need to set the dbml's connection to none whenever new stuff has been dragged onto the design surface


Partial Public Class MyDataContext


Public Sub New()


MyBase.New(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, mappingSource)


End Sub


End Class

References:

How to set the connection string in your LINQ dbml file dynamically (based on web.config)

LINQ and Web Application Connection Strings

blog comments powered by Disqus