Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Created April 7, 2017 23:01
Show Gist options
  • Save Buildstarted/b11ae6b9d9cc4a42da72c83b2e46c10e to your computer and use it in GitHub Desktop.
Save Buildstarted/b11ae6b9d9cc4a42da72c83b2e46c10e to your computer and use it in GitHub Desktop.
public class SqlBulkCopyHelper
{
public static async Task BulkInsert<T>(string connectionString, string tableName, string[] columns, IEnumerable<T> list, string[] ignoredColumns = null)
{
using (var connection = new SqlConnection(connectionString))
{
using (var bulkCopy = new SqlBulkCopy(connection))
{
await connection.OpenAsync();
bulkCopy.BulkCopyTimeout = 300;
bulkCopy.DestinationTableName = tableName;
var table = new DataTable();
if (ignoredColumns == null)
{
ignoredColumns = new string[] { };
}
var t = typeof(T);
var columnProperties = columns.Select(c =>
{
var property = t.GetProperty(c, BindingFlags.Instance | BindingFlags.Public);
return property;
}).ToList();
foreach (var column in columnProperties)
{
table.Columns.Add(column.Name, Nullable.GetUnderlyingType(column.PropertyType) ?? column.PropertyType);
}
foreach (var item in list)
{
var values = new object[columnProperties.Count];
for (var i = 0; i < columnProperties.Count; i++)
{
if (ignoredColumns.Contains(columnProperties[i].Name))
{
continue;
}
values[i] = columnProperties[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.BatchSize = table.Rows.Count;
await bulkCopy.WriteToServerAsync(table);
}
connection.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment