Passing connection string dynamically to EF

My Web APi calls the the Repository layer which uses EF Context to work with data. Context call

public MyContext()
        : base("name=MyDbContext")
    {
    }

MyDbContext is defined in WebConfig.

Now the issue is i have many copies of same database and User that logins in will determine which database to work against. I want to find a way to pass Connection String dynamically at run time.

Please advise

Thanks,

Upvotes: 1

Views: 542

Answers (3)

phil soady
phil soady

Reputation: 11328

  • If you know in advance all Databases, then put them all in app.config
  • If you know the connectionString in advance, then pass it to the dbContext the DBContext has a contructor that accepts connectionName or ConnectionString
  • Pass in DBConnection to the Context constructor

I know you asked about connection strings only, but the option to pass in a connection can prove easier to work with in EF when it comes to migration and multiple database control.

public static DbConnection GetSqlConn4DBName(string dbName) {
        var sqlConnFact = new SqlConnectionFactory(
            "Data Source=localhost; Integrated Security=True; MultipleActiveResultSets=True");
        var sqlConn = sqlConnFact.CreateConnection(dbName);
        return sqlConn;
    }


use

        var dbName = "MyDB1";
        var sqlConn = GetSqlConn4DBName(dbName);
        var context = new Ef6Ctx(sqlConn);

but equally

        var context = new Ef6Ctx("Data Source=localhost;Initial Catalog=MyDBName ;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" );

your context constructors can actually use the various constructors too.

public class Ef6Ctx3 : DbContext {
    public Ef6Ctx3() : base("ConnName"){ } // default Connection
    public Ef6Ctx3(DbConnection dbConn) : base(dbConn, true) { }
    public Ef6Ctx3(string connectionNameOrString) : base(connectionNameOrString) { }
 }

Upvotes: 1

Martin Vich
Martin Vich

Reputation: 1082

You can provide connection with connection string already specified

public MyContext(SqlConnection connection)
        : base(connection, true)
    {
    }

Upvotes: 0

Gelootn
Gelootn

Reputation: 601

just add an other constructor to your own context, if you pass a connection string into the base constructor EF will use this one.

public MyContext()
    : base("name=MyDbContext")
{
}

public MyContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

now when you call the constructor, just pass the correct Connectionstring.

Upvotes: 1

Related Questions