SqlBulkCopyColumnMappingCollection Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Collection of SqlBulkCopyColumnMapping objects that inherits from CollectionBase.
public ref class SqlBulkCopyColumnMappingCollection sealed : System::Collections::IList
public sealed class SqlBulkCopyColumnMappingCollection : System.Collections.IList
type SqlBulkCopyColumnMappingCollection = class
interface ICollection
interface IEnumerable
interface IList
Public NotInheritable Class SqlBulkCopyColumnMappingCollection
Implements IList
- Inheritance
-
SqlBulkCopyColumnMappingCollection
- Implements
Examples
The following example bulk copies data from a source table in the AdventureWorks sample database to a destination table in the same database. Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. SqlBulkCopyColumnMapping are added to the SqlBulkCopyColumnMappingCollection for the SqlBulkCopy object to create a column map for the bulk copy.
Important
This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT ... SELECT statement to copy the data.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoDifferentColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Set up the bulk copy object.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoDifferentColumns";
// The column order in the source doesn't match the order
// in the destination, so ColumnMappings must be defined.
bulkCopy.ColumnMappings.Add("ProductID", "ProdID");
bulkCopy.ColumnMappings.Add("Name", "ProdName");
bulkCopy.ColumnMappings.Add("ProductNumber", "ProdNum");
// Write from the source to the destination.
try
{
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connectionString As String = GetConnectionString()
' Open a connection to the AdventureWorks database.
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString)
sourceConnection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoDifferentColumns;", _
sourceConnection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Get data from the source table as a SqlDataReader.
Dim commandSourceData As SqlCommand = New SqlCommand( _
"SELECT ProductID, Name, ProductNumber " & _
"FROM Production.Product;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
' Set up the bulk copy object.
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(connectionString)
bulkCopy.DestinationTableName = _
"dbo.BulkCopyDemoDifferentColumns"
' The column order in the source doesn't match the order
' in the destination, so ColumnMappings must be defined.
bulkCopy.ColumnMappings.Add("ProductID", "ProdID")
bulkCopy.ColumnMappings.Add("Name", "ProdName")
bulkCopy.ColumnMappings.Add("ProductNumber", "ProdNum")
' Write from the source to the destination.
Try
bulkCopy.WriteToServer(reader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - countStart)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the sourceConnection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);" & _
"Integrated Security=true;" & _
"Initial Catalog=AdventureWorks;"
End Function
End Module
Remarks
Column mappings define the mapping between data source and the target table.
If mappings are not defined - that is, the ColumnMappings collection is empty - the columns are mapped implicitly based on ordinal position. For this to work, source and target schemas must match. If they do not, an InvalidOperationException is thrown.
If the ColumnMappings collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are ignored.
You can refer to source and target columns by either name or ordinal. You can mix by-name and by-ordinal column references in the same mappings collection.
Properties
| Name | Description |
|---|---|
| Count |
Gets the number of elements contained in the SqlBulkCopyColumnMappingCollection. |
| Item[Int32] |
Gets the SqlBulkCopyColumnMapping object at the specified index. |
Methods
| Name | Description |
|---|---|
| Add(Int32, Int32) |
Creates a new SqlBulkCopyColumnMapping and adds it to the collection, using ordinals to specify both source and destination columns. |
| Add(Int32, String) |
Creates a new SqlBulkCopyColumnMapping and adds it to the collection, using an ordinal for the source column and a string for the destination column. |
| Add(SqlBulkCopyColumnMapping) |
Adds the specified mapping to the SqlBulkCopyColumnMappingCollection. |
| Add(String, Int32) |
Creates a new SqlBulkCopyColumnMapping and adds it to the collection, using a column name to describe the source column and an ordinal to specify the destination column. |
| Add(String, String) |
Creates a new SqlBulkCopyColumnMapping and adds it to the collection, using column names to specify both source and destination columns. |
| Clear() |
Clears the contents of the collection. |
| Contains(SqlBulkCopyColumnMapping) |
Gets a value indicating whether a specified SqlBulkCopyColumnMapping object exists in the collection. |
| CopyTo(SqlBulkCopyColumnMapping[], Int32) |
Copies the elements of the SqlBulkCopyColumnMappingCollection to an array of SqlBulkCopyColumnMapping items, starting at a particular index. |
| Equals(Object) |
Determines whether the specified object is equal to the current object. (Inherited from Object) |
| GetEnumerator() |
Returns an enumerator that iterates through a collection. |
| GetHashCode() |
Serves as the default hash function. (Inherited from Object) |
| GetType() |
Gets the Type of the current instance. (Inherited from Object) |
| IndexOf(SqlBulkCopyColumnMapping) |
Gets the index of the specified SqlBulkCopyColumnMapping object. |
| Insert(Int32, SqlBulkCopyColumnMapping) |
Insert a new SqlBulkCopyColumnMapping at the index specified. |
| MemberwiseClone() |
Creates a shallow copy of the current Object. (Inherited from Object) |
| Remove(SqlBulkCopyColumnMapping) |
Removes the specified SqlBulkCopyColumnMapping element from the SqlBulkCopyColumnMappingCollection. |
| RemoveAt(Int32) |
Removes the mapping at the specified index from the collection. |
| ToString() |
Returns a string that represents the current object. (Inherited from Object) |
Explicit Interface Implementations
| Name | Description |
|---|---|
| ICollection.CopyTo(Array, Int32) |
Copies the elements of the ICollection to an Array, starting at a particular Array index. |
| ICollection.IsSynchronized |
Gets a value indicating whether access to the ICollection is synchronized (thread safe). |
| ICollection.SyncRoot |
Gets an object that can be used to synchronize access to the ICollection. |
| IList.Add(Object) |
Adds an item to the IList. |
| IList.Contains(Object) |
Determines whether the IList contains a specific value. |
| IList.IndexOf(Object) |
Determines the index of a specific item in the IList. |
| IList.Insert(Int32, Object) |
Inserts an item to the IList at the specified index. |
| IList.IsFixedSize |
Gets a value indicating whether the IList has a fixed size. |
| IList.IsReadOnly |
Gets a value indicating whether the IList is read-only. |
| IList.Item[Int32] |
Gets or sets the element at the specified index. |
| IList.Remove(Object) |
Removes the first occurrence of a specific object from the IList. |
Extension Methods
| Name | Description |
|---|---|
| AsParallel(IEnumerable) |
Enables parallelization of a query. |
| AsQueryable(IEnumerable) |
Converts an IEnumerable to an IQueryable. |
| Cast<TResult>(IEnumerable) |
Casts the elements of an IEnumerable to the specified type. |
| OfType<TResult>(IEnumerable) |
Filters the elements of an IEnumerable based on a specified type. |