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

wet*_*tes 12 c# ado.net visual-studio

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

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

Gar*_*Ray 1

将它们的连接字符串存储在 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"];
}
Run Code Online (Sandbox Code Playgroud)

现在您可以通过调用以下命令来启动您的应用程序:

MyApp.exe /live
Run Code Online (Sandbox Code Playgroud)

单独使用 MyApp.exe 或与任何其他开关一起使用将为您提供测试配置。