C# 在企业库中在运行时更改连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/326365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:18:09  来源:igfitidea点击:

Changing connection string at runtime in Enterprise Library

c#.netdatabaseconfigurationenterprise-library

提问by Gustavo Rubio

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

有没有办法在运行时更改企业库中数据库对象的连接字符串?我找到了这个链接,但它有点过时了(2005)

I've also found thisbut it seems to apply to .Net in general, I was wondering if there was something that could be done specifically for EntLib.

我也发现了这个,但它似乎一般适用于 .Net,我想知道是否可以专门为 EntLib 做一些事情。

I was just passing the connection string name to the CreateDatabase() method in DatabaseFactory object and that worked til yesterday that my project manager asked me to support more than one database instance. It happens that we have to have one database per state (one for CA, one for FL, etc...) so my software needs to cycle through all databases and do something with data but it will use the same config file.

我只是将连接字符串名称传递给 DatabaseFactory 对象中的 CreateDatabase() 方法,直到昨天我的项目经理要求我支持多个数据库实例为止。碰巧我们每个州必须有一个数据库(一个用于 CA,一个用于 FL,等等),所以我的软件需要遍历所有数据库并对数据执行某些操作,但它将使用相同的配置文件。

Thanks in advance.

提前致谢。

采纳答案by Martin Brown

If you take a look at "Enterprise Library Docs - Adding Application Code" it says this:

如果您查看“企业库文档 - 添加应用程序代码”,它会说:

"If you know the connection string for the database you want to create, you can bypass the application's configuration information and use a constructor to directly create the Database object. Because the Database class is an abstract base class, you must construct one of its derived types. The derived Database type determines the ADO.NET data provider. For example, the SqlDatabase class uses the SqlClientFactory provider, the SqlCeDatabase class uses the SqlCeProviderFactory provider, and the OracleDatabase class uses the OracleClientFactory provider. It is your responsibility to construct the appropriate type of Database class for the connection string."

”如果知道要创建的数据库的连接字符串,就可以绕过应用程序的配置信息,使用构造函数直接创建Database对象。因为Database类是抽象基类,所以必须构造它的一个派生类类型。派生的Database类型决定了ADO.NET数据提供者。例如SqlDatabase类使用SqlClientFactory提供者,SqlCeDatabase类使用SqlCeProviderFactory提供者,OracleDatabase类使用OracleClientFactory提供者。你有责任构造合适的连接字符串的数据库类的类型。”

It then goes on to give some examples. This would suggest that you should not be using the DatabaseFactory and you should be creating a new Database class for each of your different connections.

然后继续举一些例子。这表明您不应该使用 DatabaseFactory,而应该为每个不同的连接创建一个新的 Database 类。

回答by Junior Mayhé

Here's from Yang's Net Zone:

这是来自杨氏网区的:

using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;

DatabaseSettings settings = new DatabaseSettings();

// This maps to <databaseType> element in data config file
DatabaseTypeData type = new DatabaseTypeData("Sql Server", "Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
settings.DatabaseTypes.Add(type);

// This maps to <connectionString> element in data config file
ConnectionStringData connectionString = new ConnectionStringData("localhost.EntLibQuickStarts");

// Followings map to <parameter> elements in data config file
ParameterData param = new ParameterData("server", "localhost");
connectionString.Parameters.Add(param);

param = new ParameterData("database", "EntLibQuickStarts");
connectionString.Parameters.Add(param);

param = new ParameterData("integrated security", "true");
connectionString.Parameters.Add(param);

settings.ConnectionStrings.Add(connectionString);

// Too bad compiler gets confused InstanceData with System.Diagnostics.InstanceData.  It maps to <instance> element in data config file
Microsoft.Practices.EnterpriseLibrary.Data.Configuration.InstanceData instance = new    Microsoft.Practices.EnterpriseLibrary.Data.Configuration.InstanceData("localhost", "Sql Server", "localhost.EntLibQuickStarts");
settings.Instances.Add(instance);

ConfigurationDictionary configurations = new ConfigurationDictionary();

// This is how to tie DatabaseSettings with ConfigurationDictionary. It maps to <configurationSection name="dataConfiguration"> element in App.config file    configurations.Add("dataConfiguration", settings);
ConfigurationContext context = ConfigurationManager.CreateContext(configurations);

Database database = new DatabaseProviderFactory(context).CreateDatabase("localhost");

回答by bentz

look at this:Open Microsoft.practices.EnterpriseLibrary database with just a connection string

看看这个:用一个连接字符串打开 Microsoft.practices.EnterpriseLibrary 数据库

just use this follow code, you can programming create database at runtime

只需使用以下代码,您就可以在运行时编程创建数据库

database mydb = new EnterpriseLibrary.Data.Sql.SqlDatabase("connection string here");

It's solved my problem. I have a single web app using many database, according to the different subdomain in the url to connect to the different database. such as:

它解决了我的问题。我有一个使用多个数据库的 Web 应用程序,根据 url 中的不同子域连接到不同的数据库。如:

  • abc.test.com ------>using the Db_projectABC
  • def.test.com ------>using the db_ProjectDEF
  • abc.test.com ------>使用 Db_projectABC
  • def.test.com ------>使用 db_ProjectDEF

I use url-rewrite to parse the subdomain name, and use the subdomain name to chose it's database connection string which stored in the main database.

我使用url-rewrite来解析子域名,并使用子域名来选择它存储在主数据库中的数据库连接字符串。

Thanks

谢谢

回答by Sujoy Roy Chowdhury

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

我们可以使用以下代码片段连接到多个数据库。

DLLs to Add as Reference

要添加为参考的 DLL

  1. Microsoft.Practices.EnterpriseLibrary.Common.dll
  2. Microsoft.Practices.EnterpriseLibrary.Data.dll
  3. Microsoft.Practices.ServiceLocation.dll
  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");