Using Dapper For Data Access In ASP.NET Core Applications

For most of the .NET developers out there the primary choice of data access will be Microsoft's object-relational mapper Entity Framework. But there are other ORM tools available for .NET applications as well. One such popular ORM tool is Dapper. Dapper is a micro ORM which is developed by folks at StackOverflow. It is an open-source library and source code is available at Github. In this article, we will look at some features of Dapper and how to integrate Dapper with an ASP.NET Core application.
We shall be creating an ASP.NET Core Web API application with .NET Core 3.0. Most of the code will be compatible with earlier versions of .NET Core too. For using .NET Core 3.0 we need to install the .NET Core 3.0 SDK and requires Visual Studio 2019. If Visual Studio 2019 is not available we can use Visual Studio Code and DotNet CLI for development.
The application will be interacting with a SQL Server database with two tables - Movies and Directors. Use the following SQL script to create and seed the database. 
  1. CREATE DATABASE [movie-db];  
  2. USE [movie-db];  
  4. CREATE TABLE [dbo].[Directors](  
  5.     [Id] [int] IDENTITY(1,1) PRIMARY KEY,  
  6.     [Name] [nvarchar](50) NOT NULL,  
  7. );  
  9. CREATE TABLE [dbo].[Movies](  
  10.     [Id] [int] IDENTITY(1,1) PRIMARY KEY,  
  11.     [Name] [nvarchar](50) NOT NULL,  
  12.     [DirectorId] [intNOT NULL,  
  13.     [ReleaseYear] [smallintNOT NULL,  
  14.     FOREIGN KEY([DirectorId]) REFERENCES [dbo].[Directors] ([Id]));  
  16. SET IDENTITY_INSERT [dbo].[Directors] ON  
  18. GO  
  19. INSERT [dbo].[Directors] ([Id], [Name]) VALUES (1, N'Chistopher Nolan')  
  20. GO  
  21. INSERT [dbo].[Directors] ([Id], [Name]) VALUES (2, N'James Camron')  
  22. GO  
  23. SET IDENTITY_INSERT [dbo].[Directors] OFF  
  24. GO  
  25. SET IDENTITY_INSERT [dbo].[Movies] ON  
  27. GO  
  28. INSERT [dbo].[Movies] ([Id], [Name], [DirectorId], [ReleaseYear]) VALUES (1, N'Dunkirk', 1, 2017)  
  29. GO  
  30. INSERT [dbo].[Movies] ([Id], [Name], [DirectorId], [ReleaseYear]) VALUES (2, N'Interstellar', 1, 2014)  
  31. GO  
  32. INSERT [dbo].[Movies] ([Id], [Name], [DirectorId], [ReleaseYear]) VALUES (3, N'Avatar', 2, 2009)  
  33. GO  
  34. INSERT [dbo].[Movies] ([Id], [Name], [DirectorId], [ReleaseYear]) VALUES (4, N'Titanic', 2, 1997)  
  35. GO  
  36. INSERT [dbo].[Movies] ([Id], [Name], [DirectorId], [ReleaseYear]) VALUES (5, N'The Terminator', 2, 1984)  
  37. GO  
  38. SET IDENTITY_INSERT [dbo].[Movies] OFF  
Now create an ASP.NET Core Web API project. Let's name it MovieApp. Now we need to install two Nuget packages in our project - Dapper and Microsoft.Data.SqlClient. Visual Studio users can make use of the Nuget package manager of Visual Studio. As an alternative, we can install these packages with DotNet CLI also.

Unlike Entity Framework, Dapper will not translate our LINQ queries to SQL. We need to write the SQL query ourselves and shall ask Dapper to execute it for us. Dapper will execute the query and will map the result to our POCO classes. This is the main difference between EF and Dapper. Dapper will only map our query results to objects. It will not create a query for us.

Now let's write our first API for getting all the movies in the database. Create a model class named MovieModel.cs. This class shall have property names matching with column names in the query result. Then only Dapper will map the result columns with the class. If the column names are different we can make use of SQL aliases to match with the property name.

  1. public class MovieModel  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.     public string DirectorName { getset; }  
  6.     public short ReleaseYear { getset; }  
  7. }  
For interacting with the database we need to set up our connection string in our configuration. Add the following section in the appsettings.json file.
  1. "ConnectionStrings": {  
  2.     "DefaultConnection""<connection string here>"  
  3.   }  
Add a class ConnectionString in the solution. We will use this class to hold the connection string value from the configuration file and use it in our classes via dependency injection.
  1. public sealed class ConnectionString  
  2. {  
  3.     public ConnectionString(string value) => Value = value;  
  5.     public string Value { get; }  
  6. }  
Now we need to register the configuration in the ASP.NET Core dependency injection container. Add the following lines in the ConfigureServices method in Startup.cs.
  1. var connectionString = new ConnectionString(Configuration.GetConnectionString("DefaultConnection"));  
  2. services.AddSingleton(connectionString);  
Now add an interface IMovieRepository.cs with the method signature for getting all movies.
  1. public interface IMovieRepository  
  2. {  
  3.     Task<IEnumerable<MovieModel>> GetAllMovies();  
  4. }  
Add a class MovieRepository.cs which implements the IMovieRepository interface.
  1. using Dapper;  
  2. using Microsoft.Data.SqlClient;  
  3. using MovieApp.Models;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  8. public class MovieRepository : IMovieRepository  
  9. {  
  10.     private readonly ConnectionString _connectionString;  
  12.     public MovieRepository(ConnectionString connectionString)  
  13.     {  
  14.         _connectionString = connectionString;  
  15.     }  
  17.     public async Task<IEnumerable<MovieModel>> GetAllMovies()  
  18.     {  
  19.         const string query = @"SELECT m.Id, m.Name,d.Name AS DirectorName, m.ReleaseYear  
  20.                                 FROM Movies m  
  21.                                 INNER JOIN Directors d  
  22.                                 ON m.DirectorId = d.Id";  
  24.         using (var conn = new SqlConnection(_connectionString.Value))  
  25.         {  
  26.             var result = await conn.QueryAsync<MovieModel>(query);  
  27.             return result;  
  28.         }  
  29.     }  
  30. }  

In the method, we write the SQL query for fetching the movies along with their director names. Then we used the QueryAsync method of Dapper to execute the query and bind the response from the database to the MovieModel class.

We need to register the MovieRepository class in our DI container. Add the following code to ConfigureServices method.

  1. services.AddScoped<IMovieRepository, MovieRepository>();  
Add the controller class MoviesController.cs and write an action method to fetch all movies using this MovieRepository.
  1. [ApiController]  
  2. public class MoviesController : ControllerBase  
  3. {  
  4.     private readonly IMovieRepository _movieRepository;  
  6.     public MoviesController(IMovieRepository movieRepository)  
  7.     {  
  8.         _movieRepository = movieRepository;  
  9.     }  
  11.     [HttpGet("api/movies")]  
  12.     public async Task<IActionResult> GetMovies()  
  13.     {  
  14.         return Ok(await _movieRepository.GetAllMovies());  
  15.     }  
  16. }  
Now using any tool like Postman we can test this API. Run the application and call the API http://localhost:<port-number>/api/movies using Postman. We shall get a JSON response containing all movies with their director names.

Now, let's add an API for getting a movie detail by supplying its ID. In this case, we shall use a SELECT query with a WHERE clause. Add the following code in the IMovieRepository interface.

  1. Task<MovieModel> GetMovieById(int id);  
Add the method implementation in the MovieRepository class.
  1. public async Task<MovieModel> GetMovieById(int id)  
  2. {  
  3.     const string query = @"SELECT m.Id  
  4.                                 , m.Name  
  5.                                 ,d.Name AS DirectorName  
  6.                                 , m.ReleaseYear  
  7.                             FROM Movies m  
  8.                             INNER JOIN Directors d  
  9.                             ON m.DirectorId = d.Id  
  10.                             WHERE m.Id = @Id";  
  12.     using (var conn = new SqlConnection(_connectionString.Value))  
  13.     {  
  14.         var result = await conn.QueryFirstOrDefaultAsync<MovieModel>(query, new { Id = id });  
  15.         return result;  
  16.     }  
  17. }  

In this method, we use Dapper's QueryFirstOrDefaultAsync method to fetch one record. We provide the parameter value in the SQL query as an anonymous object. This is the reccommended method of supplying parameters to an SQL query via Dapper as this protects against an attack like SQL Injection.

Now let's add the controller action.

  1. [HttpGet("api/movies/{id}")]  
  2. public async Task<IActionResult> GetMovies(int id)  
  3. {  
  4.     var movie = await _movieRepository.GetMovieById(id);  
  6.     if (movie != null)  
  7.     {  
  8.         return Ok(movie);  
  9.     }  
  11.     return NotFound(new { Message = $"Movie with id {id} is not available." });  
  12. }  

When we test this API at the route http://localhost:<port-number>/api/movies/<id> we will get the details of the movie with the supplied ID from the database.

One of the powerful features of Entity Framework is the ability to fetch related data from the database. We make use of navigation properties to achieve this. But in Dapper, there is no straight forward way to achieve this. Next, we can look at how we can achieve this. We shall fetch all the directors along with their list of movies from the database.

Create two classes DirectorMovie and DirectorModel. These classes will be used to bind the SQL query response from the database.

  1. public class DirectorMovie  
  2. {  
  3.     public int Id { getset; }  
  4.     public string MovieName { getset; }  
  5.     public short ReleaseYear { getset; }  
  6. }  
  8. public class DirectorModel  
  9. {  
  10.     public int Id { getset; }  
  11.     public string Name { getset; }  
  12.     public IList<DirectorMovie> Movies { getset; }  
  13. }  
Add the following method definition in IMovieRepository.
  1. Task<IEnumerable<DirectorModel>> GetAllDirectors();  
Add the implementation in MovieRepository.
  1. public async Task<IEnumerable<DirectorModel>> GetAllDirectors()  
  2. {  
  3.     const string query = @"SELECT d.Id  
  4.                                 , d.Name  
  5.                                 , m.DirectorId  
  6.                                 , m.Id  
  7.                                 , m.Name MovieName  
  8.                                 , m.ReleaseYear  
  9.                             FROM dbo.Directors d  
  10.                             INNER JOIN dbo.Movies m  
  11.                             ON d.Id = m.DirectorId";  
  13.     using (var conn = new SqlConnection(_connectionString.Value))  
  14.     {  
  15.         var directorDictionary = new Dictionary<int, DirectorModel>();  
  17.         var result = await conn.QueryAsync<DirectorModel, DirectorMovie, DirectorModel>(  
  18.             query,  
  19.             (dir, mov) =>  
  20.             {  
  21.                 if (!directorDictionary.TryGetValue(dir.Id, out DirectorModel director))  
  22.                 {  
  23.                     director = dir;  
  24.                     director.Movies = new List<DirectorMovie>();  
  25.                     directorDictionary.Add(director.Id, director);  
  26.                 }  
  27.                 director.Movies.Add(mov);  
  28.                 return director;  
  29.             },  
  30.             splitOn: "DirectorId");  
  32.         return result.Distinct();  
  33.     }  
  34. }  

In this method, we are making use of the Multi Mapping feature of Dapper. We will supply a mapping function as the parameter of QueryAsync method of Dapper specifying how we need to populate the navigation property. We shall specify the field name of the query result set on which Dapper need to split the result set. We can make use of the split data and pass that to our mapping function to populate the navigation properties.

Now, let's add the controller action.

  1. [HttpGet("api/directors")]  
  2. public async Task<IActionResult> GetDirectors()  
  3. {  
  4.     return Ok(await _movieRepository.GetAllDirectors());  
  5. }  

When we test this API at the route http://localhost:<port-number>/api/directors we will get the details of all directors along with their list of movies from the database.

So far we were looking at SELECT statement execution using Dapper. Now we can look at how Dapper can be used to modify data. We shall now add a movie to the database.

Create a new model class CreateMovieModel.cs.

  1. public class CreateMovieModel  
  2. {  
  3.     public string Name { getset; }  
  4.     public int DirectorId { getset; }  
  5.     public short ReleaseYear { getset; }  
  6. }  
Add the following method definition in IMovieRepository.
  1. Task<int> AddMovie(CreateMovieModel movie);  
Add the implementation in MovieRepository.
  1. public async Task<int> AddMovie(CreateMovieModel movie)  
  2. {  
  3.     const string query = @"INSERT INTO dbo.Movies ([Name], [DirectorId], [ReleaseYear]) VALUES(@Name, @DirectorId, @ReleaseYear)";  
  5.     using (var conn = new SqlConnection(_connectionString.Value))  
  6.     {  
  7.         var result = await conn.ExecuteAsync(  
  8.             query,  
  9.             new { Name = movie.Name, DirectorId = movie.DirectorId, ReleaseYear = movie.ReleaseYear });  
  10.         return result;  
  11.     }  
  12. }  

We are using Dapper's ExecuteAsync method for executing the insert query. This method returns an integer value representing the number of rows modified in that SQL query. If the number is greater than zero we can be assured that our query has been executed successfully.

Add the controller action.

  1. [HttpPost("api/movies")]  
  2. public async Task<IActionResult> AddMovie(CreateMovieModel model)  
  3. {  
  4.     var result = await _movieRepository.AddMovie(model);  
  5.     if (result > 0)  
  6.     {  
  7.         return Ok(new { Message = "Movie added successfully." });  
  8.     }  
  10.     return StatusCode(500, new { Message = "Some error happened." });  
  11. }  

Test the API by providing a JSON object representing the CreateMovieModel class. Dapper will execute the query and add the records to the database.


In this article, we looked at how to use Dapper as an ORM in .NET Core applications. For detailed documentation on Dapper refer to this link.