sagheer
sagheer

Reputation: 1245

How to change connection string or pass custom connection string for EF Model

I have three database environments, Developer, Testing and Production. To setup database with sample data i created a console app where user selects environment to setup the database. I am using Entity Framework database first but stuck with how to select instance at run time. There is only one database model is it possible to change db connection at run time?

i used following code and it throws exception.

        // Truncate all Data
        if (env.Key == ConsoleKey.D)
        {
            db.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["db_dev"].ToString();
        }

Model Entities has no constructor to get Connection String..

Upvotes: 0

Views: 947

Answers (2)

BenjaminPaul
BenjaminPaul

Reputation: 2931

Ensure you have a constructor on your DbContext class that takes a connection string and then simply pass it to the base class (Entity Framework will do the rest)

public MyDbContext : DbContext
{
    public MyDbContext(string connectionString) : base (connectionString)
    {
    } 
}

Then when you instantiate your Context you simply pass in the connection string that you would like to use... example using your code above would be...

var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["db_dev"].ToString();
using (var context = new MyDbContext(connectionString))
{
}

Upvotes: 2

Michael Domashchenko
Michael Domashchenko

Reputation: 1480

When you're creating your instance of database context (db variable) there should be a constructor overload that accepts a string. That's how you can set it up with your custom connection string.

If your class that inherits from the DbContext doesn't have that overload, just create it because the base class does have it.

Upvotes: 0

Related Questions