Ivan-Mark Debono Ivan-Mark Debono - 8 months ago 56
C# Question

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.