简体   繁体   中英

How to use SqlBulkCopy and track Bulk Inserts with Glimpse

In our app we use the SqlBulkCopy class to facilitate bulk loading of our database. Recently, I've tried to add Glimpse to our solution but the code fails with an invalid cast:

System.InvalidCastException: Unable to cast object of type 'Glimpse.Ado.AlternateType.GlimpseDbConnection' to type 'System.Data.SqlClient.SqlConnection'

This is because Glimpse ADO is using a wrapped SqlConnection to make its magic possible. Unfortunately, SqlBulkCopy requires a SqlConnection so I need to cast the DbConnection .

Is there no out-of-the-box way to profile bulk insertions? The only work-around I came across with so far is:

(SqlConnection)((GlimpseDbConnection)dbConnection).InnerConnection

It's ugly since it requires referencing GlimpseDbConnection explicitly and probably it also requires adding custom time-line events to get some tracing. Is there no Glimpse add-on that solves this?

I'm using this approach (with EntityFramework's DbContext ) and it seems to work:

DbContext Db = /* ... */;

var glimpseDbConnection = Db.Database.Connection as GlimpseDbConnection;
var sqlConnection = glimpseDbConnection != null ? (SqlConnection)glimpseDbConnection.InnerConnection : (SqlConnection)Db.Database.Connection;

var glimpseDbTransaction = Db.Database.CurrentTransaction.UnderlyingTransaction as GlimpseDbTransaction;
var sqlTransaction = glimpseDbTransaction != null ? (SqlTransaction)glimpseDbTransaction.InnerTransaction : (SqlTransaction)Db.Database.CurrentTransaction.UnderlyingTransaction;

using (var bulkCopy = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.Default, sqlTransaction))
{
    var dataTable = /* ... */;
    bulkCopy.BatchSize = 2000;
    bulkCopy.BulkCopyTimeout = TimeSpan.FromMinutes(5).Seconds;
    bulkCopy.DestinationTableName = /* ... */;
    bulkCopy.WriteToServer(dataTable);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM