动态更改数据适配器连接

时间:2016-07-21 20:30:28

标签: c# .net dataadapter sqldataadapter

我使用的是C#,.NET 4.5,VS2015。

我希望能够动态更改数据适配器的连接属性。 (在运行期间)。

查看数据适配器的连接属性,连接是私有设置:

private global::System.Data.SqlClient.SqlConnection _connection;

private void InitConnection() {
            this._connection = new global::System.Data.SqlClient.SqlConnection();
            this._connection.ConnectionString = global::Audit.Properties.Settings.Default.LoggingConnectionString;
        }

是否可以在运行时更改表适配器的连接?

修改

有趣的是,对于具有select命令的表适配器,连接属性是公共的,因此更改它不是问题。对于带插入命令的适配器,连接是私有的,我不知道如何更改它。当然,我说的是直接从服务器资源管理器拖动到数据集的设计视图的组件。

select命令的示例(生成为内部全局):

 internal global::System.Data.SqlClient.SqlConnection Connection {
            get {
                if ((this._connection == null)) {
                    this.InitConnection();
                }
                return this._connection;
            }

insert命令的示例(作为私有生成):

 private void InitCommandCollection() {
            this._commandCollection = new global::System.Data.IDbCommand[1];
            this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand();
            ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Connection = new global::System.Data.SqlClient.SqlConnection(global::Audit.Properties.Settings.Default.LoggingConnectionString1);

1 个答案:

答案 0 :(得分:0)

我能够通过在TableAdapter中创建自己的ConnectionString属性来克服此限制。您只需要确保它是TableAdapter命名空间的一部分。

public partial class MyTableAdapter
{
    public string ConnectionString
    {
        set
        {
            if ((this._commandCollection == null))
            {
                this.InitCommandCollection();
            }

            for (int index = 0; index < this._commandCollection.Length; index++)
            {
                this._commandCollection[index].Connection.ConnectionString = value;
            }
        }
    }
}