Created
June 12, 2018 10:19
-
-
Save DaniCCardenas/e8817309aece1eacfbdc58854b40f05a 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 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); | |
} | |
} |
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
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