0

I have an application that can make a connection to a database. There are many instances of this database use by numerous sites. I want to use migration to update the database schema when the program loads. I have got this working. However, my connection string stored in app.config has been blanked out(by me) And I use a connection string builder to take the users login details and server/database username/password and alter the connection string within the dbcontext to connect to their own database.

Eg.                  source.Database.Connection.ConnectionString "TrustServerCertificate=False;Encrypt=true;Integrated Security =" + integratedSecuity + ";data source=" + Server + ";initial catalog=" + Database + ";persist security info=true;"+ ";MultipleActiveResultSets=True;App=EntityFramework\" providerName = \"System.Data.SqlClient";

I have utilized a snippet from Stackoverflow to check for changes in my entity framework on program start.

Db = Internal_ConnectionTools.ChangeDatabase(Db, Txt_Database.Text, Txt_Server.Text, Txt_User.Text,Txt_Password.Text);
            LabDatabase LD = new LabDatabase(Db.Database.Connection.ConnectionString);
            Database.SetInitializer<LabDatabase>(
                new MigrateDatabaseToLatestVersion<LabDatabase, Configuration>());
            LD.Database.Initialize(true);

The problem I am having is that it keeps pointing back to the connection string in my App.config file and throwing an error that the Initial catalogue has not been defined.(because there is nothing defined by design)

If I fill the app.config connection string with my credentials, my database updates as expected.

How can I ensure that Entityobject.Database.Initialize() will use my updated custom string and update the users database instead of defaulting to the App.config string?

Kezzla
  • 189
  • 1
  • 8

1 Answers1

0

Ok, after a bit more digging I found the answer here

How do I set a connection string config programmatically in .net?

It describes and provides a method utilizing reflection to allow alteration of the connection string within an instance of App.config.

I have made some very small alterations to the original code to suit my purposes. My amended method is below.

private void SpoofAppConfig(string connectionStringName, string connectionString)
    {
        var settings = ConfigurationManager.ConnectionStrings[connectionStringName];

        var fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

        fi.SetValue(settings, false);

        settings.ConnectionString = connectionString;
    }

This will not change anything within the actual app.config file.

Calling this method prior to migration will allow you to run migration with a custom connection string without the issues I was facing in the initial post.

Kezzla
  • 189
  • 1
  • 8