在运行时更改实体模型数据库

时间:2012-06-20 20:16:02

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

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

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

2 个答案:

答案 0 :(得分:1)

通常这是通过配置文件设置完成的。 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);

答案 1 :(得分:1)

Justin Pihony有正确的答案。 如果你想同时访问两个数据库(来回切换)而不是更改配置并重新启动应用程序.....那么你有一个用于Train的设置和一个用于Prod的设置,那么你就像这样做你的上下文: / p>

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