Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Using SQL bulk copy with your LINQ-to-SQL datacontext

0.00/5 (No votes)
23 Feb 2012CPOL 7.3K  
If the order of your columns is different in the LINQ to SQL class from that in the database, then you also need to add a column mapping to the bulk copier. Otherwise you get mysterious errors in some of the loaded columns!In my simple fix, I assume that the names match even if the order may...

If the order of your columns is different in the LINQ to SQL class from that in the database, then you also need to add a column mapping to the bulk copier. Otherwise you get mysterious errors in some of the loaded columns!


In my simple fix, I assume that the names match even if the order may have been messed about with. In this case you can add the following:


C#
// Assume that the property name matches that in the database.
...

table.Columns.Add(new DataColumn(property.Name, propertyType));

bulkCopy.ColumnMappings.Add(
  new SqlBulkCopyColumnMapping(property.Name, property.Name));
...

For extra credit, the mapping could be pulled out of the LINQ attributes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)