开发者

How to Fill a DataSet with TableMapping instead of TableName

According to msdn http://msdn.microsoft.com/en-us/library/ks92fwwh.aspx

The DataTableMapping name can be passed in place of the DataTable name to the Fill method of the DataAdapter.

The code below is wi开发者_如何转开发th TableName "Employee"

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, FirstName, LastName " +
      "FROM Employees AS Emp " +
      "WHERE EmployeeID = 9";
    OleDbDataAdapter mySqlDataAdapter = new OleDbDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();

    DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employees", "dtEmployee");

    Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable);
    Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);

    myDataTableMapping.ColumnMappings.Add("EmployeeID", "dtEmployeeId");
    mySqlConnection.Open();
    mySqlDataAdapter.Fill(myDataSet, "Employee");
    mySqlConnection.Close();    

    DataTable myDataTable = myDataSet.Tables["dtEmployee"];
    foreach (DataRow myDataRow in myDataTable.Rows)
    {
      Console.WriteLine("ID = " + myDataRow["dtEmployeeId"]);
      Console.WriteLine("FirstName = " + myDataRow["FirstName"]);
      Console.WriteLine("LastName = " + myDataRow["LastName"]);
    }   
        Console.ReadLine();
    }

}

If I pass "dtEmployee" in Fill

mySqlDataAdapter.Fill(myDataSet, "dtEmployee");

It says dtEmployeeId doesn't belong to datatable dtEmployee ! How can I use my ColumnMappings then ?


I believe you have your arguments in the wrong order. From the MSDN document:

The following example creates a DataTableMapping named AuthorsMapping for the Authors table.

workAdapter.TableMappings.Add("AuthorsMapping", "Authors");

I looks like you're creating a DataTableMapping named Employees for the dtEmployee table. Try:

DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("dtEmployee", "Employees");

To clarify, right now you're creating a Mapping called Employees. You are then filling the DataTable called dtEmployee. Since dtEMployeeId is on your mapping Employees and not your datatable dtEmployee it is throwing the right error "dtEmployeeId doesn't belong to datatable dtEmployee"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜