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