-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlBulkCopyInserter.cs
63 lines (52 loc) · 1.77 KB
/
SqlBulkCopyInserter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BulkInsertInvestigation
{
public class SqlBulkCopyInserter : IInserter
{
private readonly string connectionString;
private readonly int batchSize;
public SqlBulkCopyInserter(string connectionString, int batchSize)
{
this.connectionString = connectionString;
this.batchSize = batchSize;
}
public void Insert(IEnumerable<Customer> batch)
{
var dataTable = batch.ToDataTable();
using (var bulkCopy = new SqlBulkCopy(connectionString, (SqlBulkCopyOptions)0))
{
bulkCopy.NotifyAfter = batchSize;
bulkCopy.SqlRowsCopied += bulkCopy_SqlRowsCopied;
bulkCopy.DestinationTableName = "Customers";
bulkCopy.BulkCopyTimeout = 0;
ConfigureColumnMappings(bulkCopy, dataTable);
try
{
bulkCopy.WriteToServer(dataTable);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}
}
private void ConfigureColumnMappings(SqlBulkCopy bulkCopy, DataTable dataTable)
{
foreach (DataColumn column in dataTable.Columns)
{
bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
}
private void bulkCopy_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine("Inserted {0} rows...", e.RowsCopied);
}
}
}