实体框架改变现有DbContext的数据库 [英] Entity Framework changing database of existing DbContext

查看:85
本文介绍了实体框架改变现有DbContext的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码(例如,在我的存储库的构造函数中):

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

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

然后稍后我做:

db.Database.Connection.ConnectionString = mySQLconnectionstring;

我需要重新设置实体?

推荐答案

坏主意。您应该创建新的上下文实例:

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.

由于模型相同,模型构建(这在EF中是最重要的性能)只会发生一次。我无法想象,还有什么可以迫使你重新使用上下文实例。

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.

这篇关于实体框架改变现有DbContext的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆