【问题标题】:.net 3.5 modify DataSet query at runtime.net 3.5 在运行时修改DataSet查询
【发布时间】:2012-12-20 11:29:16
【问题描述】:

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

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

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

你知道更好的技术吗?

【问题讨论】:

  • (然后我根据修改后的查询创建一个新的 OracleCommand,然后将其分配给我的适配器的 SelectCommand 属性)

标签: .net sql oracle .net-3.5 dataset


【解决方案1】:

所以由于没有人回答,我发布了我在这里使用的解决方法(继承类)。前言:当你将一个 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);
              }
          }
      }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多