Skip to content

Instantly share code, notes, and snippets.

@mattritchie
Forked from jferguson/gist:1681480
Last active December 20, 2017 23:47
Show Gist options
  • Save mattritchie/90d6f5100ce38563ab0883ea66324dcf to your computer and use it in GitHub Desktop.
Save mattritchie/90d6f5100ce38563ab0883ea66324dcf to your computer and use it in GitHub Desktop.
SqlBulkCopy Generic List<T>
public static class SqlBulkCopyForDapper
{
public static void BulkInsert<T>(this IDbConnection connection, IList<T> list)
{
var conn = connection as SqlConnection;
if (conn == null)
throw new Exception("conn is not SQLConnection");
if(conn.State != ConnectionState.Open)
conn.Open();
using (var bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.BatchSize = list.Count;
bulkCopy.DestinationTableName = typeof(T).Name;
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