R – Two .NET projects, one DB connection string

asp.net-mvcconfigurationconnection-stringnet

I have a .NET solution containing two projects:

  • An ASP.NET MVC project, 'Website'
  • A class library, 'Models'

The 'Models' project contains a Linq-to-SQL data-context along with a few partial classes that extend the database objects.

The connection string is defined in the web.config of the 'Website' project.

However the 'Models' project seems to have its own app.config where the database connection is defined separately.

This means that if the connection string changes, I'll have to update both projects.

Is there a way I can centralize the connection string to one place, and still have both projects use it?

Best Answer

Create a partial class that is the same as your data context and use this code to force the usage of the web.config string as opposed to the app.config. Put the partial class in the same location as your model in the class library.

public partial class YourDataContext 
{
    partial void OnCreated()
    {
        ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["PrimaryConnectionString"];

        if (cs != null)
        {
             this.Connection.ConnectionString = cs.ConnectionString;
        }
    }
}

See this question for more info Preferred Method for connection string in class library
RichardOD posted a link to what I think best describes our problem LINQ To SQL and the Web.Config ConnectionString Value