LINQ to SQL DataContext Constructors

If you use LINQ to SQL (which if you're considering it, you should consider going to the ADO.NET Entity Framework), the DataContext object that's automatically generated for you has a variety of constructors that you can use.  One of the more important constructors is the one that takes a connection string.  This connection string overrides the default connection string generated.

When you make a change to the model, the LINQ data context takes the connection that you drag/drop from, and puts it in the application settings.  So if you create your context like:

CustomDataContext ctx = new CustomDataContext();

This connection will use this value.  I like to use the override, which takes a connection string:

CustomDataContext ctx = new CustomDataContext(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);

I usually use the static factory approach to create this, as:

public static class ContextFactory
{
    public static CustomDataContext GetInstance()
    {
         return new CustomDataContext(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
    }
}

This works nicely, and centralizes the location of the connection string being used.

Published Monday, February 23, 2009 6:59 PM by bmains
Filed under:

Comments

No Comments