1

I have a c# project ("MainProject") which references another c# project ("UserManager") in my solution. UserManager has a local database (a "Service-based Database", .mdf).

By adding this database to UserManager, Visual Studio 2015 by default created a connectionstring entry in App.config of UserManager...

<connectionStrings>
        <add name="UserManager.Properties.Settings.TPHWDatabaseConnectionString"
            connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TPHWDatabase.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient" />
</connectionStrings>

... and an entry in Properties.Settings named as the name field of the App.config entry containing the following value:

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TPHWDatabase.mdf;Integrated Security=True

In my C# code of the UserManager project I create my SqlConnection object using the following lines:

    // Establish conenction to database
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["UserManager.Properties.Settings.TPHWDatabaseConnectionString"].ConnectionString;
    sqlConnection.Open();

This all works fine running the UserManager project by itself. The database file (".mdf") is also included in the MainProject's bin folders. When running the MainProject however, "ConfigurationManager.ConnectionStrings["UserManager.Properties.Settings.TPHWDatabaseConnectionString"]" will be null and I will get a nullpointer exception for calling ".ConnectionString" on it. Which seems reasonable since I have no Access to "UserManager.Properties.Settings" and "App.config" from MainProject.

So my question is: What is a clean way to reference UserManager ( in MainProject) that will keep the database working?

EDIT

I now just copied the connection string as is to the App.config file of my MainProject and set the exact same setting to Properties.Setting. This seems to work and was rather easy. But is is it still the cleanest way to do so?

Mthenn
  • 189
  • 1
  • 14

1 Answers1

0

Add a connection string to your web.config referring to the database instead of attaching the DB file. something like this

<connectionStrings>
    <add connectionString="Server=.\sqlexpress;Initial Catalog=myDB;Integrated Security=True;" name="mydbconnection" />
 </connectionStrings>

And read it like below:

ConnectionStringSettings ConnectionString = ConfigurationManager.ConnectionStrings["mydbconnection"]
user5534263
  • 138
  • 12
  • First of all, thanks for the fast response. But I would like to keep the local database file in the MainProject's binaray folder in order to keep the MainProject executable independent when moving it to other systems. But I did not fully understand your new connection string either and don't know if it still would do what I want. – Mthenn Feb 23 '16 at 16:26