bulk insert dapper in csharp

To bulk insert data using Dapper in C#, you can use SqlBulkCopy class which is a part of ADO.NET. Here is an example code snippet on how to do a bulk insert using Dapper:

main.cs
using System.Data.SqlClient;
using Dapper;

var connection = new SqlConnection("YourConnectionStringHere");

// Sample data to insert
var myList = new List<MyClass>
{
    new MyClass { FirstName = "John", LastName = "Doe" },
    new MyClass { FirstName = "Jane", LastName = "Doe" },
    new MyClass { FirstName = "Alice", LastName = "Bob" }
};

connection.Open();

// Begin a new transaction
var transaction = connection.BeginTransaction();

try
{
    // Create a new SQLBulkCopy object
    var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction);

    // Set the destination table name
    bulkCopy.DestinationTableName = "MyTable";

    // Map the class properties to the destination table columns
    bulkCopy.ColumnMappings.Add("FirstName", "First");
    bulkCopy.ColumnMappings.Add("LastName", "Last");

    // Write the data to the destination table
    bulkCopy.WriteToServer(myList);

    // Commit the transaction
    transaction.Commit();
}
catch (Exception ex)
{
    // Rollback the transaction if an error occurs
    transaction.Rollback();

    throw new Exception("An error occurred while bulk inserting data using Dapper.", ex);
}
finally
{
    // Close the connection
    connection.Close();
}
1238 chars
49 lines

In the above code snippet, we first open a SqlConnection and begin a new transaction. We then create a new instance of SqlBulkCopy class and set the DestinationTableName and ColumnMappings properties. Finally, we call the WriteToServer method passing in the list of data to be inserted. Lastly, we commit the transaction and close the connection. In case of any exceptions, we catch and rollback the transaction.

gistlibby LogSnag