EF 6 interceptor to set connectionstring

386 views Asked by At

How can I use EF6 interceptors to dynamically set the connection string for a db context? I am using code-first to work with the database.

Basically in my application I have this scenario:

In my app.config file I have defined 3 database connection strings:

  <connectionStrings>
    <add name="Db1DbContext" connectionString="Data Source=***;Initial Catalog=***;Integrated Security=false;User Id=***;Password=***" providerName="System.Data.SqlClient"/>
    <add name="Db2DbContext" connectionString="Data Source=***;Initial Catalog=***;Integrated Security=false;User Id=***;Password=***" providerName="System.Data.SqlClient"/>
    <add name="Db3DbContext" connectionString="Data Source=***;Initial Catalog=***;Integrated Security=false;User Id=***;Password=***" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The 3 databases have the same structure. Based on a key that the user enters when the app starts, I need to use one of the 3 databases so I need to dynamically read the right connection string from the config file and set it to the db context so I will work with the right database.

1

There are 1 answers

0
Marko M. On BEST ANSWER

Simplest possible solution is to put user entered key in some global variable(or somewhere where you can access it later) and just call a method to instantiate your DbContext with correct connection string. Something like this:

public MyDbContext CreateContext()
{
    if (user_entered_key == "one")
    {
        return new MyDbContext("Db1DbContext");
    }
    else if (user_entered_key == "two")
    {
        return new MyDbContext("Db2DbContext");
    }
    else
    {
        return new MyDbContext("Db3DbContext");
    }
}