Map table and column names : DataTableMapping « Database ADO.net « C# / C Sharp






Map table and column names


using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

class Mappings
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText = "SELECT ID AS MappedID, FirstName, LastName " +
      "FROM Employee AS Emp " +
      "WHERE ID = 9";
    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();
    mySqlConnection.Open();
    mySqlDataAdapter.Fill(myDataSet, "Employee");
    mySqlConnection.Close();

    DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employee", "Emp");

    myDataSet.Tables["Employee"].TableName = "Emp";

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

    myDataTableMapping.ColumnMappings.Add("ID", "MappedID");

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








Related examples in the same category