-
Notifications
You must be signed in to change notification settings - Fork 0
/
TableValueParameterInserter.cs
55 lines (46 loc) · 1.69 KB
/
TableValueParameterInserter.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;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BulkInsertInvestigation
{
public class TableValueParameterInserter : IInserter
{
private string connectionString;
private int batchSize;
public TableValueParameterInserter(string connectionString, int batchSize)
{
this.connectionString = connectionString;
this.batchSize = batchSize;
}
public void Insert(IEnumerable<Customer> dataRecords)
{
int inserted = 0;
IEnumerable<Customer> batch = null;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "InsertCustomers";
command.CommandType = CommandType.StoredProcedure;
var parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.CustomersTableType";
parameter.ParameterName = "@Customers";
command.Parameters.Add(parameter);
do
{
batch = dataRecords.Skip(inserted).Take(this.batchSize);
var dataTable = batch.ToDataTable();
parameter.Value = dataTable;
command.ExecuteNonQuery();
inserted += batchSize;
Console.WriteLine("Inserted {0} rows", inserted);
} while (batch.Any());
}
}
}
}