Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two .NET projects, one DB connection string?

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?

like image 601
Jonathan Avatar asked Aug 24 '09 14:08

Jonathan


3 Answers

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

like image 111
Breadtruck Avatar answered Nov 07 '22 15:11

Breadtruck


That's fine. Put the Model's connection string in the Web.config and forget (delete) the Model's config file.

The DataContext also takes in a connection string in its constructor so you can specify it this way too (perhaps not on one line though):

DataContext context = new DataContext(ConfigurationManager.ConnectionStrings["TheKey"].ConnectionString);

Edit- based on your comments to other answers it looks like you are doing something wrong. If you are doing that, then the generated code will use the default setting value.

System.Configuration.DefaultSettingValueAttribute("Data Source=SERVER;Initial Catalog=XYZ;Integrated Security=True")].

You might be making the mistake of not specifying the connection string properly in the Web.config file.

like image 39
RichardOD Avatar answered Nov 07 '22 14:11

RichardOD


I'd say that you should keep the configuration of the product in the web project's web.config, and then inject the configuration you use into the model project.

like image 36
Thomas Lundström Avatar answered Nov 07 '22 14:11

Thomas Lundström