0

If I have the following code (for example, in the constructor of my repository):

var db = new MyDbContext();
var entity = db.Set<Customer>();

Then later I do:

db.Database.Connection.ConnectionString = mySQLconnectionstring;

Do I need to 're-set' the entity?

4
  • What do you want to achieve by that? Commented Nov 28, 2013 at 9:05
  • This is really something you can just try and see if it works. Commented Nov 28, 2013 at 9:05
  • I have multiple databases based on the same model, and I want to change the database at a later stage. Commented Nov 28, 2013 at 9:06
  • Why not to create another Context for each DB? Commented Nov 28, 2013 at 9:07

3 Answers 3

4

Bad idea. You should create new context instance:

var db1 = new MyDbContext("connstr1");
var db2 = new MyDbContext("connstr2");

Otherwise you'll get more difficulties, than benefits you're supposing (if this ever possible). Note, that every context instance keeps local cache of materialized entities and tracks their changes.

Since the model is the same, model building (which is most significant performance hit in EF) will happen just once. I can't imagine, what else could force you to re-use context instances.

Sign up to request clarification or add additional context in comments.

1 Comment

Is the connectionstring passed to the dbcontext an sql connection string or an entity connection string?
1

Write new class file and add this method to your context

public partial class YourEntitities
{
    public void SetDatabase(string dataBase)
    {
        string connString = Database.Connection.ConnectionString;
        Regex rgx = new Regex(@"(?<=initial catalog=)\w+");
        string newconnString = rgx.Replace(connString, dataBase);
        //string  = connString.Replace("{database}", dataBase);
        Database.Connection.ConnectionString = newconnString;
    }
}

Comments

0

if you want to use same context for multiple database, you can do that. one way is changing connection string of context in the memory. before changing db that you want to use. Call this piece of code:

        var connStr="YOUR_NEW_DB_CONNECTION_STRING_HERE";
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
        connectionStringsSection.ConnectionStrings["YOUR_DB_CONNECTION_STRING_NAME_EG_CONN_STR"].ConnectionString = connStr;
        connectionStringsSection.ConnectionStrings["YOUR_DB_CONNECTION_STRING_NAME_EG_CONN_STR"].ProviderName = "System.Data.EntityClient";
        config.Save();
        ConfigurationManager.RefreshSection("connectionStrings");

Comments

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.