FillDataSet 的解析

使用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);
        }

转载于:https://www.cnblogs.com/perock/archive/2012/11/19/2778212.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值