【问题标题】:Change Entity model database at runtime在运行时更改实体模型数据库
【发布时间】:2012-06-21 04:47:06
【问题描述】:

如何切换我的实体模型在运行时连接的数据库?

例如,如果我有一个训练数据库和一个生产数据库,我如何通过更改应用程序中的设置来让我的应用程序在两者之间切换。

【问题讨论】:

  • 配置文件中的连接字符串?我对 WPF 不太熟悉,但是在 WCF 或 ASP.NET 中,会有一个 web.config。

标签: c# .net entity-framework-4


【解决方案1】:

贾斯汀·皮奥尼有正确的答案。 如果您想同时访问两个数据库(来回切换)而不是更改配置并重新启动应用程序.....那么您有两个设置,一个用于训练,一个用于生产,那么您可以像这样执行上下文:

string training = ConfigurationManager.ConnectionStrings["Train"].ToString();
string production = ConfigurationManager.ConnectionStrings["Prod"].ToString();

.....
EFContext context = null;
if (InTraining) 
   context = new EfContext(training);
else
   context = new EfContext(production);

【讨论】:

  • 这正是我想要的。谢谢。
【解决方案2】:

通常这是通过配置文件设置完成的。 Here is the MSDN on EF connection stringshere is some more info on it, basically saying it should be in your app.config

而且,如果你想从代码中获得一些东西,here is a code project:

string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);

System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;

dataContext = new SampleEntities(ecb.ConnectionString);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多