Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class BulkUploadToSql<T>
{
public IList<T> InternalStore { get; set; }
public string TableName { get; set; }
public int CommitBatchSize { get; set; } = 1000;
public SqlConnection Connection { get; set; }
public async Task Commit()
{
if (InternalStore.Count > 0)
{
DataTable dt;
int numberOfPages = (InternalStore.Count / CommitBatchSize) +
(InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
{
dt = InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
await BulkInsertAsync(dt);
}
}
}
public async Task BulkInsertAsync(DataTable dt)
{
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
Connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
) {DestinationTableName = TableName};
await bulkCopy.WriteToServerAsync(dt);
}
}
var objBulk = new BulkUploadToSql<Client>()
{
InternalStore = clients,
TableName = "TableName",
CommitBatchSize = 5000,
Connection = conn
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment