forked from PhenX/PhenX.EntityFrameworkCore.BulkInsert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerBulkInsertProvider.cs
More file actions
64 lines (53 loc) · 2.14 KB
/
SqlServerBulkInsertProvider.cs
File metadata and controls
64 lines (53 loc) · 2.14 KB
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
using JetBrains.Annotations;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using PhenX.EntityFrameworkCore.BulkInsert.Options;
namespace PhenX.EntityFrameworkCore.BulkInsert.SqlServer;
[UsedImplicitly]
internal class SqlServerBulkInsertProvider : BulkInsertProviderBase<SqlServerDialectBuilder>
{
public SqlServerBulkInsertProvider(ILogger<SqlServerBulkInsertProvider>? logger = null) : base(logger)
{
}
//language=sql
/// <inheritdoc />
protected override string CreateTableCopySql => "SELECT {2} INTO {0} FROM {1} WHERE 1 = 0;";
//language=sql
/// <inheritdoc />
protected override string AddTableCopyBulkInsertId => $"ALTER TABLE {{0}} ADD {BulkInsertId} INT IDENTITY PRIMARY KEY;";
/// <inheritdoc />
protected override string GetTempTableName(string tableName) => $"#_temp_bulk_insert_{tableName}";
/// <inheritdoc />
protected override async Task BulkInsert<T>(
bool sync,
DbContext context,
IEnumerable<T> entities,
string tableName,
PropertyAccessor[] properties,
BulkInsertOptions options,
CancellationToken ctk
)
{
var connection = (SqlConnection) context.Database.GetDbConnection();
var sqlTransaction = context.Database.CurrentTransaction!.GetDbTransaction() as SqlTransaction;
using var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, sqlTransaction);
bulkCopy.DestinationTableName = tableName;
bulkCopy.BatchSize = options.BatchSize ?? 50_000;
bulkCopy.BulkCopyTimeout = options.GetCopyTimeoutInSeconds();
foreach (var prop in properties)
{
bulkCopy.ColumnMappings.Add(prop.Name, prop.ColumnName);
}
if (sync)
{
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
bulkCopy.WriteToServer(new EnumerableDataReader<T>(entities, properties));
}
else
{
await bulkCopy.WriteToServerAsync(new EnumerableDataReader<T>(entities, properties), ctk);
}
}
}