Created
January 26, 2012 07:12
-
-
Save jferguson/1681480 to your computer and use it in GitHub Desktop.
SqlBulkCopy Generic List<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void BulkInsert<T>(string connection, string tableName, IList<T> list) | |
{ | |
using (var bulkCopy = new SqlBulkCopy(connection)) | |
{ | |
bulkCopy.BatchSize = list.Count; | |
bulkCopy.DestinationTableName = tableName; | |
var table = new DataTable(); | |
var props = TypeDescriptor.GetProperties(typeof(T)) | |
//Dirty hack to make sure we only have system data types | |
//i.e. filter out the relationships/collections | |
.Cast<PropertyDescriptor>() | |
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System")) | |
.ToArray(); | |
foreach (var propertyInfo in props) | |
{ | |
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name); | |
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType); | |
} | |
var values = new object[props.Length]; | |
foreach (var item in list) | |
{ | |
for (var i = 0; i < values.Length; i++) | |
{ | |
values[i] = props[i].GetValue(item); | |
} | |
table.Rows.Add(values); | |
} | |
bulkCopy.WriteToServer(table); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Similar to paully21 i forked the code and made a few modifications: