In order for Dapper to do bulk inserts, you need a third-party library:
Once you have this package, bulk inserts are at your fingertips. Async is supported in a rather special way. Lets see how it’s done.
First of all, this is my table:
CREATE TABLE [dbo].[Favorites](
[rowId] [int] IDENTITY(1,1) NOT NULL,
[userKey] [int] NOT NULL,
[favoriteId] [nvarchar](255) NULL,
[lastModified] [datetime] NULL,
[isDeleted] [bit] NULL,
[created] [datetime] NULL,
CONSTRAINT [PK_Favorites] PRIMARY KEY CLUSTERED
(
[rowID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Dapper is an O/R mapper, so you’ll need a model class that represents the SQL table. The model class does not need to have the same name as the SQL table, but the fields need to be the same:
public class FavoriteDTO
{
public int RowId { get; set; }
public int UserKey { get; set; }
public string FavoriteId { get; set; }
public DateTime? LastModified { get; set; }
public bool? IsDeleted { get; set; }
public DateTime? Created { get; set; }
}
Now all you have to do is to create a repository with a bulk insert method:
using Dapper;
using Z.Dapper.Plus;
using Microsoft.Data.SqlClient;
using System.Data;
namespace MyCode
{
public class FavoritesRepository
{
public FavoritesRepository()
{
}
public async Task BulkInsertAsync(IEnumerable<FavoriteDTO> favorites)
{
using var connection = new SqlConnection("your-sql-connection-string");
// Specifying that the "FavoriteDTO" model class should be bulk inserted
// into the "Favorites" SQL table
DapperPlusManager.Entity<FavoriteDTO>().Table("Favorites");
// Do the actual bulk insert
await connection.BulkActionAsync(x => x.BulkInsert<FavoriteDTO>(favorites));
}
}
}
That’s it. You are now a Dapper expert. Happy coding.
MORE TO READ:
- Dapper Github repo
- Dapper Plus Bulk Insert Documentation
- Bulk insert in Dapper from Michał Białecki
- Bulk Insert in Dapper into MS SQL by Zoltan Halasz
- C# Using Dapper as your SQL framework in .NET Core by briancaos
- C# Dapper Trim String Values by briancaos
- C# Dapper convert numbers to 2 decimals by briancaos