-
Notifications
You must be signed in to change notification settings - Fork 0
/
DapperInserter.cs
55 lines (49 loc) · 1.63 KB
/
DapperInserter.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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace BulkInsertInvestigation
{
public class DapperInserter : IInserter
{
private string connectionString;
private int batchSize;
public DapperInserter(string connectionString, int batchSize)
{
this.connectionString = connectionString;
this.batchSize = batchSize;
}
public void Insert(IEnumerable<Customer> dataRecords)
{
int inserted = 0;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var transaction = connection.BeginTransaction();
foreach (Customer customer in dataRecords)
{
try
{
connection.Execute(
@"INSERT INTO Customers(Email, Name, [Address], IsActive, Latitude, Longitude)
VALUES (@Email, @Name, @Address, @IsActive, @Latitude, @Longitude)",
customer,
transaction);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (++inserted%batchSize == 0)
{
Console.WriteLine("Inserted {0} customers", inserted);
}
}
transaction.Commit();
}
}
}
}