简体   繁体   English

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

[英]Best way to set strongly typed dataset connection string at runtime?

My Windows Forms application uses a strongly typed dataset created using the designer in Visual Studio.我的 Windows 窗体应用程序使用使用 Visual Studio 中的设计器创建的强类型数据集。 At runtime I would like to be able to select either the live or test database.在运行时,我希望能够选择实时数据库或测试数据库。

What is the best way to programmatically set the connection string for the dataset at runtime?在运行时以编程方式为数据集设置连接字符串的最佳方法是什么?

Connection property in TableAdapters is defined as internal . TableAdapters 中的连接属性定义为internal

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

So in case your TypedDataset is not in the same assembly as your main windows forms app, you will not be able to access Connection property.因此,如果您的 TypedDataset 与您的主 Windows 窗体应用程序不在同一个程序集中,您将无法访问 Connection 属性。 This problem might popup later when you refactor your dataset code and move it into a seperate project which will produce its own independant assembly.当您重构数据集代码并将其移动到将生成其自己独立程序集的单独项目中时,此问题可能会在稍后弹出。

To solve this problem, you can do as mentioned below.要解决此问题,您可以按如下所述进行操作。

create partial class for your TableAdapter and add another constructor beside the default public parameterless constructor.为您的 TableAdapter 创建部分类并在默认公共无参数构造函数旁边添加另一个构造函数。 Assuming TableAdapter type as MyTableAdapter假设 TableAdapter 类型为 MyTableAdapter

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

    public void SetConnection(SqlConnection connection)
    {
        this._connection = connection;
    }
}

You will need to do this for as many as TableAdapters you have in your project.您需要为项目中的 TableAdapter 执行此操作。 TableAdapter does not have any common base class but thanks that they are declared as partial classes so we are able to do it the way mentioned above. TableAdapter 没有任何公共基类,但感谢它们被声明为部分类,因此我们能够按照上述方式进行操作。

Now at runtime, you can create an instance of your TableAdapter like this..现在在运行时,您可以像这样创建 TableAdapter 的实例。

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

or may be even assign it later after you create the TableAdapter instance with default parameterless public constructor..或者甚至可以在您使用默认的无参数公共构造函数创建 TableAdapter 实例之后再分配它..

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

By default the Connection property is set to be internal .默认情况下, Connection属性设置为internal This can be changed in the DataSet's designer.这可以在数据集的设计器中更改。

  1. Right-click the TableAdapter.右键单击 TableAdapter。

在此处输入图片说明

  1. Then change the ConnectionModifier property to public .然后将ConnectionModifier属性更改为public

在此处输入图片说明

  1. You can now access the Connection property in your project.您现在可以访问项目中的Connection属性。
var loginsTableAdapter = new MyDataSetTableAdapters.LoginsTableAdapter();
loginsTableAdapter.Connection.ConnectionString = _myConnectionString;

It's a pain to edit the designer file.编辑设计器文件很痛苦。

I created a Settings entry under "User' called 'ConnectionString', which makes Visual Studio create an application string 'Connection String1' when you add a strongly typed data set.我在“用户”下创建了一个名为“ConnectionString”的设置条目,这使 Visual Studio 在您添加强类型数据集时创建应用程序字符串“Connection String1”。

So, I just replace all 'ConnectionString1' with 'ConnectionString' in the dataset designer file, and that will allow you to use a 'User' string setting to load your connection string at runtime.因此,我只是将数据集设计器文件中的所有“ConnectionString1”替换为“ConnectionString”,这将允许您使用“User”字符串设置在运行时加载您的连接字符串。

IMHO it's a shortcoming allowing users to modify connection strings at runtime.恕我直言,这是一个缺点,允许用户在运行时修改连接字符串。 (Anyone listening in Redmond?) (有人在雷德蒙德听吗?)

Store connection strings for them both in an app.config and then you can switch based on a command line / start up switch.将它们的连接字符串存储在 app.config 中,然后您可以根据命令行/启动开关进行切换。 Or if you want to give the user the flexibility you could give them an options page where they can select which connection to use.或者,如果您想为用户提供灵活性,您可以为他们提供一个选项页面,他们可以在其中选择要使用的连接。

Below is the code to read a start-up switch:下面是读取启动开关的代码:

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"];
}

So now you start your app by calling:所以现在你通过调用以下命令来启动你的应用程序:

MyApp.exe /live

Using MyApp.exe alone or with any other switch will get you the test configuration.单独使用 MyApp.exe 或与任何其他开关一起使用将为您提供测试配置。

Re: wethercotes comment回复:wethercotes 评论

The wizard stores the connection string when you set up the dataset, but that doesn't mean you can't make it dynamic.当您设置数据集时,向导会存储连接字符串,但这并不意味着您不能使其动态化。 How depends on which version you are using, but in general if you expand the files under your dataset you will find a file like Designer.cs, or DataTableNameAdapter.xsd.如何取决于您使用的版本,但通常如果您展开数据集下的文件,您会找到类似 Designer.cs 或 DataTableNameAdapter.xsd 的文件。 You can open those files and search for _connection.您可以打开这些文件并搜索 _connection。 This is usually a private variable and is set in an init function in the class.这通常是一个私有变量,并在类的 init 函数中设置。

You can make the setting dynamic by adding code like the following:您可以通过添加如下代码使设置动态化:

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

Note that if you regenerate the dataset you will likely lose this section of code, and without refactoring the dataset you may have to add it to several objects.请注意,如果您重新生成数据集,您可能会丢失这部分代码,并且如果不重构数据集,您可能必须将其添加到多个对象中。

Using the TableAdapterManager might work for you.使用 TableAdapterManager 可能对您有用。 Please read more at: http://rajmsdn.wordpress.com/2009/12/09/strongly-typed-dataset-connection-string/请阅读更多信息: http : //rajmsdn.wordpress.com/2009/12/09/strongly-typed-dataset-connection-string/

Best Solution I have found so far:迄今为止我找到的最佳解决方案:

Add another program setting which holds your preffered connection string as set by the client at runtime (eg. newConnectionString)添加另一个程序设置,其中包含客户端在运行时设置的首选连接字符串(例如 newConnectionString)

then before using the Table Adapter:然后在使用表适配器之前:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM