0

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..

2 Answers 2

2

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))
{
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

No, There's no constructor that takes Connection String. So i think i should create a partial class to have a constructor that takes Connection String?
See my answer below.. you simply create a constructor on your Context class that takes a string and pass it to the base class...
Context class says it's auto generated class and editing may change behavior of app. Manual changes to this file will be overwritten if the code is regenerated.
In that case simply create a partial class and add the constructor into that instead, same thing applies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.