LINQ to SQL Connection Strings

by Cliff 17. May 2009

When using the LINQ to SQL designer surface in Visual Studio, each time you add an object (table, procedure, etc), you will end up adding connection string information to your config file.  This can be confusing as the names used for the connection string may be different then what you want to use and you may end up with multiple connection strings, especially if you have multiple developers working on the same project.

To address this issue, you can:

  1. Create a partial class for your data context and create a parameter-less constructor as follows

    public partial class LinqAppDataContext
        {
            public LinqAppDataContext()
                : base(ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString())
            {

            }
        }

    In this example, I already have a LinqAppDataContext class, and I am creating a partial class that calls the constructor on the base class that takes a connection string.  I then pull this connection string from the config file.

  2. Step 1 is a one time setup.  The remaining steps need to be followed each time you add a new object to the designer surface

  3. Add a new object to the designer surface (for example, drag a table from the Server Explorer)

  4. Click on an empty section of the designer surface (dbml file)

  5. In the properties window, go to Connection, then clear the information from the Connection String property and then set the Application Settings property to false.  By doing this, the parameter-less constructor from step 1 above will kick in and pull the connection string from your config file.

  6. Verify that no extra connection strings have been added to your projects settings or config files
Hopefully this will help you in clearly knowing which connection string will be used with your LINQ to SQL context classes.

Related posts

Comments are closed

Cliff Gray's Info

Cliff Gray
Developer/Founder GrayTechnology.com.

E-mail me Send mail

Authors

Calendar

<<  May 2019  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

Blogroll

Download BlogEngine.NET

Download at CodePlex

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2019

Subscribe