Matthew Jones

My team is finally embarking on a new project that we can use ASP.NET Core for. I've also been waiting a long time to use the "micro-ORM" Dapper in one of our projects, and this new one fits the bill: we need incredible performance and minimal coding.

So what happens when the winds of change meet the waves of hope? You get mixed-up nautical imagery! And, hopefully, some insight into ASP.NET Core.

In this post, we're going to create a very simple ASP.NET Core application which uses Dapper to access data.

With all of that said, let's climb aboard the tutorial Titanic!

Hmmm. Maybe that wasn't the best metaphor.

Step 0: The Sample Project

As with many of my posts, there is a sample project over on GitHub. You might want to use that to follow along with this post.

Step 1: Get the NuGet Package

First things first, we need to grab the NuGet package for Dapper. In Visual Studio, you can do this by right-clicking on your project file and selecting Manage NuGet Packages and then search for the Dapper package, like so:

With that installed, let's try creating a repository.

Step 2: Create an Employee Class and Repository

For this demo, I am not going to go over how to create a database or show a demo database with sample data; I don't have one available and it's a pain to make one. So let's assume we have a table Employee with columns for FirstName, LastName, ID, and DateOfBirth. We can make a corresponding C# class for this table, like so:

The problem is: how do we pass that connection string to the repository so it can create a SqlConnection object for Dapper to use?

ASP.NET Core introduces a new IConfiguration object which can be injected into other classes. That injected instance will contain a method called GetConnectionString which we can use to obtain our connection string from the appSettings.json files. So, let's inject IConfiguration like so:

Step 5: Employee by ID

Let's first create a method to return employees by their ID.

To start, let's remember that the way Dapper works is by processing raw SQL and then mapping it to an object. Because our table columns and object properties share the same names, we don't need to do any special mapping here.