在运行时设置强类型数据集连接字符串的最佳方法?

我的Windows窗体应用程序使用在Visual Studio中使用设计器创建的强类型数据集。 在运行时,我希望能够选择实时或测试数据库。

在运行时以编程方式为数据集设置连接字符串的最佳方法是什么?

TableAdapters中的Connection属性定义为internal

internal global::System.Data.SqlClient.SqlConnection Connection 

因此,如果您的TypedDataset与主Windows窗体应用程序不在同一个程序集中,您将无法访问Connection属性。 当您重构数据集代码并将其移动到将生成其自己的独立程序集的单独项目时,此问题可能会稍后弹出。

要解决此问题,您可以按照下面的说明进行操作。

为TableAdapter创建分部类,并在默认的无参数构造函数旁边添加另一个构造函数。 假设TableAdapter类型为MyTableAdapter

 public partial class MyTableAdapter { public MyTableAdapter(SqlConnection connection) { thisSetConnection(connection); this.ClearBeforeFill = true; } public void SetConnection(SqlConnection connection) { this._connection = connection; } } 

您需要为项目中的TableAdapter执行此操作。 TableAdapter没有任何公共基类,但是由于它们被声明为部分类,所以我们能够按照上面提到的方式进行操作。

现在,在运行时,您可以像这样创建TableAdapter的实例。

 SqlConnection connection; //create the connection here at runtime.. MyTableAdapter adapter = new MyTableAdapter(connection); 

或者甚至可以在使用默认无参数公共构造函数创建TableAdapter实例后再分配它。

 SqlConnection connection; //create the connection here at runtime.. MyTableAdapter adapter = new MyTableAdapter(); adapter.(connection); 

在app.config中存储它们的连接字符串,然后您可以根据命令行/启动开关进行切换。 或者,如果您想为用户提供灵活性,可以为他们提供一个选项页面,供他们选择要使用的连接。

以下是读取启动开关的代码:

 string[] args = Environment.GetCommandLineArgs(); // The first (0 index) commandline argument is the exe path. if (args.Length > 1) { if (Array.IndexOf(args, "/live") != -1) { // connection string = // ConfigurationSettings.AppSettings["LiveConString"]; } } else { // connection string = // ConfigurationSettings.AppSettings["TestConString"]; } 

所以现在你通过调用启动你的应用程序:

 MyApp.exe /live 

单独使用MyApp.exe或使用任何其他交换机将获得测试配置。

回复:wethercotes评论

设置数据集时,向导会存储连接字符串,但这并不意味着您无法使其动态化。 具体取决于您使用的版本,但一般情况下,如果展开数据集下的文件,您将找到类似Designer.cs或DataTableNameAdapter.xsd的文件。 您可以打开这些文件并搜索_connection。 这通常是一个私有变量,并在类中的init函数中设置。

您可以通过添加如下代码来使设置动态化:

 public string ConnectionString { get { return this._connection.ConnectionString; } set { if (this._connection == null) { this._connection = new System.Data.SqlClient.SqlConnection(); } this._connection.ConnectionString = value; } } 

请注意,如果重新生成数据集,则可能会丢失此部分代码,如果不重构数据集,则可能需要将其添加到多个对象中。

使用TableAdapterManager可能适合您。 请阅读更多信息: http : //rajmsdn.wordpress.com/2009/12/09/strongly-typed-dataset-connection-string/

到目前为止我找到的最佳解决方案:

添加另一个程序设置,该设置保存客户端在运行时设置的优先连接字符串(例如newConnectionString)

然后在使用表适配器之前:

 this.myTableAdapter.Connection.ConnectionString = Properties.Settings.Default.newConnectionString; 

编辑设计器文件很痛苦。

我在“User”下创建了一个名为’ConnectionString’的设置条目,这使得Visual Studio在添加强类型数据集时会创建一个应用程序字符串’Connection String1’。

因此,我只是在数据集设计器文件中用’ConnectionString’替换所有’ConnectionString1’,这将允许您使用’User’字符串设置在运行时加载连接字符串。

恕我直言,这是一个缺点,允许用户在运行时修改连接字符串。 (有人在雷德蒙德听吗?)