Building Restful API with ASP.Net Core and Dapper

Oğuz Berkay Yerdelen
3 min readAug 17, 2019

Heya folks

This’ll be my first hurrah as an article so that I hope you like the language of this article. Actually, I was thinking about writing some articles about Asp.Net Core but then decided to make it as API and added Dapper as “micro-ORM” so let’s start with Dapper.

What is Dapper?

Dapper is a micro ORM or it is a simple object mapper framework that helps to map the native query output to a domain class or a C# class. Usually, ORM tools work a bit cumbersome but still Dapper is quite fast compared to other ORMs primarily because of its lightweight. It also allows us to write Query easily, just like in the entity framework but much quicker and simple. Simplicity is another area where Dapper crushes other ORMS. In a few lines of code, can easily get data out from the database.

Faster than Garfield finds pizza

In this post, we’re gonna create a quite simple API that uses Dapper as a micro-ORM.

STEPS TO CREATE STRUCTURE OF PROJECT

At the end of the steps project structure should be like this.

Project structure
  1. First, create a table by using the SQL Script.

2. Create a web API project

3. In order to use Dapper, We have to install the package by via Package Manager Console

Install-Package Dapper -Version 1.60.6

4. The next step will be creating the POCO class which is corresponding to the created Product Table and name it Product.

5. From now we’re ready to create a Repository that we’re gonna use at the controller so let's start as create a folder which is named Services and add subfolder into it as Queries name. After that add CommandText class to the subfolder.

This approach provides an integrated structure for SQL queries that we will use with dapper so service class will be much clearer. Add IProductRepository and Productrepository to the Services folder.

Also here is BaseRepository for the domain repositories. This base repository is basically including the helper's methods to connect the DataBase. We can say that they’re kind of data access side of our application.

If you look at the above code block, you can see that there’re 3helper methods to avoid writing the same code for each repository method. At this point, I prefer to use it as a generic and much cleaner code on repository since we’re using magic queries on Dapper.

6. Register Services into the projects.

7. Finally creating Controller part :)

Summary

Now the codes became smoother and tidier. We have implemented several endpoints for the product table and I hope u enjoyed while reading the article. See u in next article

You can download the source code from Github

Thanks to Fuji Nguyen for contribution since he changed project structure and added to Async/Await to support high volume web API calls. I also updated the medium blog for the newcomers.

--

--