-
Notifications
You must be signed in to change notification settings - Fork 0
/
EfInserter.cs
74 lines (59 loc) · 2.25 KB
/
EfInserter.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
64
65
66
67
68
69
70
71
72
73
74
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 EfInserter
{
private readonly string connectionString;
private readonly int batchSize;
public EfInserter(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))
using (var context = new EfContext(connection))
{
context.Configuration.AutoDetectChangesEnabled = false;
context.Configuration.ValidateOnSaveEnabled = false;
do
{
batch = dataRecords.Skip(inserted).Take(this.batchSize);
foreach (Customer customer in batch)
{
context.Customers.Add(customer);
}
context.SaveChanges();
inserted += batchSize;
Console.WriteLine("Inserted {0} rows", inserted);
} while (batch.Any());
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var transaction = connection.BeginTransaction();
do
{
batch = dataRecords.Skip(inserted).Take(this.batchSize);
connection.Execute(
@"INSERT INTO Customers(Email, Name, [Address], IsActive, Latitude, Longitude)
VALUES (@Email, @Name, @Address, @IsActive, @Latitude, @Longitude)",
batch,
transaction);
inserted += batchSize;
Console.WriteLine("Inserted {0} rows", inserted);
} while (batch.Any());
transaction.Commit();
}
}
}
}