看了SqlHelper类的FillDataset方法,当用SqlDataAdapter填充数据到数据集(包括强类型数据集)时,如果超过二个表,就会出现表映射错误。
private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames,
params SqlParameter[] commandParameters)
{
if( connection == null ) throw new ArgumentNullException( "connection" );
if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
// Create a command and prepare it for execution
SqlCommand command = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
// Create the DataAdapter & DataSet
using( SqlDataAdapter dataAdapter = new SqlDataAdapter(command) )
{
// Add the table mappings specified by the user
if (tableNames != null && tableNames.Length > 0)
{
string tableName = "Table";
for (int index=0; index < tableNames.Length; index++)
{
if( tableNames[index] == null || tableNames[index].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(tableName, tableNames[index]);
tableName += (index + 1).ToString();
}
}
上面的
dataAdapter.TableMappings.Add(tableName, tableNames[index]);
修改成
dataAdapter.TableMappings.Add((index>0)?(tableName+index.ToString()):tableName, tableNames[index]);
就行了。