Created
April 7, 2017 23:01
-
-
Save Buildstarted/b11ae6b9d9cc4a42da72c83b2e46c10e to your computer and use it in GitHub Desktop.
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 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