-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSqlServerBulkInsertProvider.cs
More file actions
71 lines (58 loc) · 2.34 KB
/
SqlServerBulkInsertProvider.cs
File metadata and controls
71 lines (58 loc) · 2.34 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
65
66
67
68
69
70
71
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, SqlServerBulkInsertOptions>
{
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}";
protected override SqlServerBulkInsertOptions GetDefaultOptions() => new()
{
BatchSize = 50_000,
};
/// <inheritdoc />
protected override async Task BulkInsert<T>(
bool sync,
DbContext context,
IEnumerable<T> entities,
string tableName,
PropertyAccessor[] properties,
SqlServerBulkInsertOptions options,
CancellationToken ctk
)
{
var connection = (SqlConnection) context.Database.GetDbConnection();
var sqlTransaction = context.Database.CurrentTransaction!.GetDbTransaction() as SqlTransaction;
using var bulkCopy = new SqlBulkCopy(connection, options.CopyOptions, sqlTransaction);
bulkCopy.DestinationTableName = tableName;
bulkCopy.BatchSize = options.BatchSize;
bulkCopy.BulkCopyTimeout = options.GetCopyTimeoutInSeconds();
bulkCopy.EnableStreaming = options.EnableStreaming;
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);
}
}
}