Changing connection string at runtime in Enterprise Library

后端 未结 4 574
星月不相逢
星月不相逢 2020-12-16 04:33

Is there a way to change the connection string of a DataBase object in Enterprise Library at runtime? I\'ve found this link but its a little bit outdated (2005)

I\'v

4条回答
  •  -上瘾入骨i
    2020-12-16 04:47

    We can use the following code snippet to connect to multiple databases.

    DLLs to Add as Reference

    1. Microsoft.Practices.EnterpriseLibrary.Common.dll
    2. Microsoft.Practices.EnterpriseLibrary.Data.dll
    3. Microsoft.Practices.ServiceLocation.dll

    The snippet:

    var builder = new ConfigurationSourceBuilder();
    
            builder.ConfigureData()
                   .ForDatabaseNamed("LocalSqlServer1")
                     .ThatIs.ASqlDatabase()
                     .WithConnectionString(@"Data Source=PCNAME\SQLEXPRESS;Initial Catalog=ContactDB;Integrated Security=True")
                   .ForDatabaseNamed("LocalSqlServer2")
                     .ThatIs.ASqlDatabase()
                     .WithConnectionString(@"Data Source=PCNAME\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True");
    
            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
    
    Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);      
    
    Database destinationDatabase = DatabaseFactory.CreateDatabase("LocalSqlServer2");      
    

提交回复
热议问题