我的Windows Forms应用程序使用Visual Studio中的设计器创建的强类型数据集。在运行时,我希望能够选择实时数据库或测试数据库。
在运行时,最佳的编程方式是什么以设置数据集的连接字符串?
我的Windows Forms应用程序使用Visual Studio中的设计器创建的强类型数据集。在运行时,我希望能够选择实时数据库或测试数据库。
在运行时,最佳的编程方式是什么以设置数据集的连接字符串?
TableAdapters中的连接属性被定义为internal。
internal global::System.Data.SqlClient.SqlConnection Connection
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);
SqlConnection connection;
//create the connection here at runtime..
MyTableAdapter adapter = new MyTableAdapter();
adapter.SetConnection(connection);
Connection
属性被设置为internal
。这可以在DataSet的设计器中更改。
ConnectionModifier
属性更改为public
。Connection
属性。var loginsTableAdapter = new MyDataSetTableAdapters.LoginsTableAdapter();
loginsTableAdapter.Connection.ConnectionString = _myConnectionString;
编辑设计文件真是一件痛苦的事情。
我在“用户”下创建了一个名为“ConnectionString”的设置项,这样当您添加强类型数据集时,Visual Studio会创建一个应用程序字符串“ConnectionString1”。
因此,我只需在数据集设计器文件中将所有的“ConnectionString1”替换为“ConnectionString”,这将允许您在运行时使用“用户”字符串设置来加载连接字符串。
在我看来,允许用户在运行时修改连接字符串是一个缺陷。(有人在Redmond听吗?)
将它们的连接字符串存储在 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/
this.myTableAdapter.Connection.ConnectionString = Properties.Settings.Default.newConnectionString;