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

标签 c# visual-studio ado.net

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

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

最佳答案

TableAdapter 中的连接属性定义为内部

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. 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.

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

为您的 TableAdapter 创建部分类,并在默认的公共(public)无参数构造函数旁边添加另一个构造函数。假设 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 没有任何公共(public)基类,但感谢它们被声明为部分类,因此我们能够按照上述方式进行操作。

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

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

或者甚至可以在您使用默认无参数公共(public)构造函数创建 TableAdapter 实例之后分配它..

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

关于c# - 在运行时设置强类型数据集连接字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695491/

相关文章:

c# - 如何将 System.Type 解析为 System.Data.DbType?

c# - 将 C# dll 导入到 C++ 托管代码 (.NET)

c# - 集成测试和 TDD

visual-studio - 有人在云端开发吗? (所以基本上使用 rdp 来访问你的 devenv)

visual-studio - 在 VS 中查找和替换正则表达式的通配符

c# - 使用 OracleDatareader 时,字段数据类型可以逐行更改吗

c# - .Net 如何为部分类创建构造函数?

c# - EF6如何自定义复数

c - 尝试从 C 代码获取 Windows 版本

c# - 通过 GetSchema 确定主键列