Dapper.NET Bulk inserts Async Bulk Copy

30% OFF - 9th Anniversary discount on Dapper Plus until December 15 with code: ZZZANNIVERSARY9


This sample uses a ToDataReader method described here Creating a Generic List DataReader for SqlBulkCopy.

This can also be done using non-async methods.

public class Widget
    public int WidgetId {get;set;}
    public string Name {get;set;}
    public int Quantity {get;set;}

public async Task AddWidgets(IEnumerable<Widget> widgets)
    using(var conn = new SqlConnection("{connection string}")) {
        await conn.OpenAsync();

        using(var bulkCopy = new SqlBulkCopy(conn)) {
            bulkCopy.BulkCopyTimeout = SqlTimeoutSeconds;
            bulkCopy.BatchSize = 500;
            bulkCopy.DestinationTableName = "Widgets";
            bulkCopy.EnableStreaming = true;

            using(var dataReader = widgets.ToDataReader())
                await bulkCopy.WriteToServerAsync(dataReader);

Got any Dapper.NET Question?