0

我敢肯定以前有人问过这样的问题,但我似乎无法准确找到我需要的东西。假设我在我的 VS 2010 .NET 3.5 项目中添加了一个 DataSet 组件 - 它可以正常执行和填充,并且非常易于使用。但是,如果我想在运行时对其查询进行小修改(基于各种用户输入)怎么办?

我知道我可以使用参数来做到这一点,但是如果对查询的修改具有更多的结构特征,比如省略参数等怎​​么办?

在生成的代码中,我看到它公开了 CommandCollection 属性,但它受到保护,因此我不能从数据集外部使用它 - 除非:) 我创建了一个从生成的适配器对象继承的虚拟类并通过以下方式公开公开 CommandCollection 属性力(这就是我所做的)-但这不是有点尴尬吗?

你知道更好的技术吗?

4

1 回答 1

0

所以由于没有人回答,我发布了我在这里使用的解决方法(继承类)。前言:当你将一个 DataSet 类从 VS 2010 工具箱拖到设计视图中的表单(例如 MainForm)时,会生成三件事:

  • 一个数据集(包含表和数据实例)
  • 一个 DataAdapter(描述如何填充上述数据集)
  • 一个 BindingSource(将上面的 DataSet 绑定到 Form 上的控件)

上面生成的类的定义以及所需的查询等最终存储在一个 XSD 文件中,并且在每次构建期间,这些类的代码都是从 XSD 生成的。

  // MyTableAdapter is a VS2010 AUTOGENERATED class
  // (generated during DataSet wizard)
  // thankfully, MyTableAdapter exposes protected CommandCollection attribute
  class MyAdapter : MyTableAdapter
  {
      public System.Data.OracleClient.OracleCommand[] Commands
      {
          get { return CommandCollection; }
      }
  }

  class MainForm : Form
  {
      private void btnQuery_Click(object sender, EventArgs e)
      {
          // create new OracleCommand to substitute the SelectCommand in autogenerated adapter
          using (OracleCommand cmd = new OracleCommand())
          {
              MyAdapter m = new MyAdapter(); // dummy instance used just to retrieve saved query
              if (m.Commands.Length > 0)
              {
                   cmd.Connection = mainDbConnection;
                   cmd.CommandText = m.Commands[0].CommandText.Replace('someText', 'someOtherText'); // do whatever changes to the query
                   cmd.CommandType = CommandType.Text;
                   cmd.Parameters.Add(...); // optionally, if needed

                   //myTableAdapter is a Designer generated instance of MyTableAdapter
                   //but I can substitute its SelectCommand with something else
                   myTableAdapter.Adapter.SelectCommand = cmd;
                   myTableAdapter.Adapter.Fill(this.myDataSet.MyTable);
              }
          }
      }
  }
于 2013-01-04T11:56:15.800 回答