Effectively insert list of objects with Dapper

If you are using Dapper as your sql/object mapper for .Net, you often find yourself inserting lists of objects. There are several ways of doing it, but maybe you're not doing it the fastest way possible (apart from hand-coding)?

What most people do is iterating over the list add execute the insert for each item like this:

foreach (var item in myList
{
    connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", item);
}

but this is not the fastest way becuse the Dapper Execute() extension takes a list as parameter and iterates for you:

connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", myList);

I tested by inserting 10.000 simple objects into an SqlCe database and clocked the resuts. The first option took 1.88 seconds, and the second took 1.19 seconds! So, letting Dapper iterate and insert is not twice as fast, but almost!

To install Dapper, run the following command in the Package Manager Console

PM> Install-Package Dapper

1 Comment

Comments have been disabled for this content.