这有效:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
public class MyClass
{
public static void Main()
{
OleDbConnection mySqlConnection =new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data\nwind.Mdb");
OleDbCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT EmployeeID AS MappedID, FirstName, LastName " +
"FROM Employees AS Emp " +
"WHERE EmployeeID = 9";
OleDbDataAdapter mySqlDataAdapter = new OleDbDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Employees");
mySqlConnection.Close();
DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employees", "dtEmployee");
myDataSet.Tables["Employees"].TableName = "dtEmployee";
Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable);
Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);
myDataTableMapping.ColumnMappings.Add("EmployeeID", "MappedId");
DataTable myDataTable = myDataSet.Tables["dtEmployee"];
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("ID = " + myDataRow["MappedId"]);
Console.WriteLine("FirstName = " + myDataRow["FirstName"]);
Console.WriteLine("LastName = " + myDataRow["LastName"]);
}
Console.ReadLine();
}
}
只需将“MappedId”更改为“NewMappedId”:
myDataTableMapping.ColumnMappings.Add("EmployeeID", "NewMappedId");
Console.WriteLine("ID = " + myDataRow["NewMappedId"]);
到“NewMappedId”之类的其他内容,程序将在运行时崩溃,说NewMappedId不属于表dtEmployee。这是一个错误吗?!
答案 0 :(得分:2)
这里没有错误。
如果更改绑定数据集的内容,则此错误是正常的,因为您不再匹配绑定的基础架构。