2013-05-25 9 views
1

У меня есть несколько баз данных SQL с одной и той же схеме .say (Database1, database2 ....)Выбор базы данных динамически в Entity Framework

Как я динамически выбирать базы данных в Entity Framework модели во время выполнения? .Since они имеют ту же схему, нет смысла импортировать все модели данных перед началом работы.

+1

Вы можете изменить соединение сущностей во время выполнения, чтобы изменить базу данных SQL. Вы проверили это? – Mojtaba

+0

Вы пробовали переходить в другую строку соединения в класс ObjectContext или DbContext? – Steven

ответ

3

Вы можете изменить строку подключения к базе данных, как это:

DataModelContainer context = new DataModelContainer(
        ConnectionOperation.CreateEntityConnection()); 

И это CreateEntityConnection Метод:

internal static EntityConnection CreateEntityConnection() 
      { 
       // Start out by creating the SQL Server connection string 
       SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(); 

       // Set the properties for the data source. The IP address network address 
       sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["Connection"]; 
       // The name of the database on the server 
       sqlBuilder.UserID = "sa"; 
       sqlBuilder.Password = "12345"; 
       sqlBuilder.InitialCatalog = "DatabaseName"; 
       sqlBuilder.IntegratedSecurity = true; 
       sqlBuilder.MultipleActiveResultSets = true; 
       // Now create the Entity Framework connection string 
       EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); 
       //Set the provider name. 
       entityBuilder.Provider = "System.Data.SqlClient"; 
       // Set the provider-specific connection string. 
       entityBuilder.ProviderConnectionString = sqlBuilder.ToString(); 

       // Set the Metadata location. 
       entityBuilder.Metadata = @"res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl"; 

       // Create and entity connection 
       EntityConnection conn = new EntityConnection(entityBuilder.ToString()); 
       return conn; 
      } 
Смежные вопросы