使用ADO.net填充数强类型据集中多张表时,需要注意了:
1.select查询语句顺序会影响到DataAdapter.Tablemappings.add方法.
如果不使用映射,那么ADO将自动使用Table、Table1、Table2这样的表名去填充DataSet.
第一条Select自然对应的Table.
2.要想让ADO自动将表对应的填充到强类型DatsSet中的表,需使用TableMappings.Add()
参考代码:
public virtual void FillDataset(IDbCommand command, DataSet dataSet, string[] tableNames)
{
bool flag = false;
this.CleanParameterSyntax(command);
if (command.Connection.State != ConnectionState.Open)
{
command.Connection.Open();
flag = true;
}
using (IDbDataAdapter dataAdapter = null)
{
dataAdapter = this.GetDataAdapter();
dataAdapter.SelectCommand = command;
if ((tableNames != null) && (tableNames.Length > 0))
{
string str = "Table";
for (int i = 0; i < tableNames.Length; i++)
{
if ((tableNames[i] == null) || (tableNames[i].Length == 0))
{
throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames");
}
dataAdapter.TableMappings.Add(str + ((i == 0) ? "" : i.ToString()), tableNames[i]);
}
}
dataAdapter.Fill(dataSet);
if (flag)
{
command.Connection.Close();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from Employees ");
strSql.Append("select * from Products ");
strSql.Append("select * from Customers ");
string connstr = ConfigurationManager.ConnectionStrings["test2.Properties.Settings.NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand cmd = new SqlCommand(strSql.ToString(),conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.TableMappings.Add("Table", "Employees");
ad.TableMappings.Add("Table1", "Products");
ad.TableMappings.Add("Table2", "Customers");
ad.Fill(dataSet11);
}