1+ using System . Diagnostics ;
12using System . Runtime . CompilerServices ;
23
34using Microsoft . EntityFrameworkCore ;
1112
1213namespace PhenX . EntityFrameworkCore . BulkInsert ;
1314
14- internal abstract class BulkInsertProviderBase < TDialect , TOptions > ( ILogger ? logger ) : BulkInsertProviderUntyped < TDialect , TOptions >
15+ internal abstract class BulkInsertProviderBase < TDialect , TOptions > ( ILoggerFactory ? loggerFactory ) : BulkInsertProviderUntyped < TDialect , TOptions >
1516 where TDialect : SqlDialectBuilder , new ( )
1617 where TOptions : BulkInsertOptions , new ( )
1718{
19+ private ILogger ? _logger ;
20+ private ILogger ? logger => _logger ??= loggerFactory ? . CreateLogger ( GetType ( ) ) ;
1821 protected virtual string BulkInsertId => "_bulk_insert_id" ;
1922
2023 protected abstract string AddTableCopyBulkInsertId { get ; }
@@ -144,7 +147,15 @@ private async Task<string> PerformBulkInsertAsync<T>(
144147 activity ? . AddTag ( "tempTable" , tempTableRequired ) ;
145148 activity ? . AddTag ( "synchronous" , sync ) ;
146149
150+ var sw = Stopwatch . StartNew ( ) ;
147151 await BulkInsert ( sync , context , tableInfo , entities , tableName , columns , options , ctk ) ;
152+ sw . Stop ( ) ;
153+
154+ if ( logger != null )
155+ {
156+ Log . BulkInsertExecuted ( logger , sw . ElapsedMilliseconds , tableName ) ;
157+ }
158+
148159 return tableName ;
149160 }
150161
@@ -254,16 +265,17 @@ protected virtual Task DropTempTableAsync(bool sync, DbContext dbContext, string
254265 return Task . CompletedTask ;
255266 }
256267
257- protected static async Task ExecuteAsync (
268+ protected async Task ExecuteAsync (
258269 bool sync ,
259270 DbContext context ,
260271 string query ,
261272 CancellationToken ctk )
262273 {
263- var command = context . Database . GetDbConnection ( ) . CreateCommand ( ) ;
274+ using var command = context . Database . GetDbConnection ( ) . CreateCommand ( ) ;
264275 command . Transaction = context . Database . CurrentTransaction ! . GetDbTransaction ( ) ;
265276 command . CommandText = query ;
266277
278+ var sw = Stopwatch . StartNew ( ) ;
267279 if ( sync )
268280 {
269281 // ReSharper disable once MethodHasAsyncOverloadWithCancellation
@@ -273,5 +285,11 @@ protected static async Task ExecuteAsync(
273285 {
274286 await command . ExecuteNonQueryAsync ( ctk ) ;
275287 }
288+ sw . Stop ( ) ;
289+
290+ if ( logger != null )
291+ {
292+ Log . ExecutedDbCommand ( logger , sw . ElapsedMilliseconds , query ) ;
293+ }
276294 }
277295}
0 commit comments