简体   繁体   中英

Entity Framework changing database of existing DbContext

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?

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.

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");

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM